読者です 読者をやめる 読者になる 読者になる

Bridgeパターン

実装の階層、機能の階層、委譲

% find . -name "*.java" -print0 |xargs -0 cat                                []
public class CountDisplay extends Display {
	public CountDisplay(DisplayImpl impl) {
		super(impl);
	}

	public void multiDisplay(int times) {
		open();
		for (int i = 0; i < times; i++) {
			print();
		}
		close();
	}
}
public class Display {
	private DisplayImpl impl;

	public Display(DisplayImpl impl) {
		this.impl = impl;
	}

	public void open() {
		impl.rawOpen();
	}

	public void print() {
		impl.rawPrint();
	}

	public void close() {
		impl.rawClose();
	}

	public final void display() {
		open();
		print();
		close();
	}

}
public abstract class DisplayImpl {
	public abstract void rawOpen();

	public abstract void rawPrint();

	public abstract void rawClose();

}
public class Main {

	public static void main(String[] args) {
		Display d1 = new Display(new StringDisplayImpl("Hello World"));
		d1.display();
		CountDisplay d2 = new CountDisplay(new StringDisplayImpl("Hello World"));
		d2.multiDisplay(3);
	}

}
public class StringDisplayImpl extends DisplayImpl {
	private String str;
	private int width;

	public StringDisplayImpl(String str) {
		this.str = str;
		this.width = str.getBytes().length;
	}

	@Override
	public void rawOpen() {
		printLine();
	}

	@Override
	public void rawPrint() {
		System.out.println("|" + str + "|");
	}

	@Override
	public void rawClose() {
		printLine();
	}

	public void printLine() {
		System.out.print("+");
		for (int i = 0; i < width; i++) {
			System.out.print("-");
		}
		System.out.println("+");
	}

}
+-----------+
|Hello World|
+-----------+
+-----------+
|Hello World|
|Hello World|
|Hello World|
+-----------+