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

Template Methodパターン

Java

これはいつか使うのだろうな。もう使ってるまである。

% find . -name "*.java" -print0 |xargs -0 cat                                []
public abstract class AbstractDisplay {
	protected abstract void open();

	protected abstract void print();

	protected abstract void close();

	public final void display() {
		open();
		for (int i = 0; i < 5; i++) {
			print();
		}
		close();
	}
}
public class CharDiaplay extends AbstractDisplay {
	private char ch;

	public CharDiaplay(char ch) {
		this.ch = ch;
	}

	@Override
	protected void open() {
		System.out.print("<<");
	}

	@Override
	protected void print() {
		System.out.print(ch);
	}

	@Override
	protected void close() {
		System.out.println(">>");
	}

}
public class Main {

	public static void main(String[] args) {
		AbstractDisplay d1 = new CharDiaplay('a');
		AbstractDisplay d2 = new StringDisplay("Hello World!");
		AbstractDisplay d3 = new StringDisplay("こんちには");
		d1.display();
		d2.display();
		d3.display();
	}

}
public class StringDisplay extends AbstractDisplay {
	private String str;
	private int width;

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

	@Override
	protected void open() {
		printLine();
	}

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

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

	@Override
	protected void close() {
		printLine();
	}

}
<<aaaaa>>
+------------+
|Hello World!|
|Hello World!|
|Hello World!|
|Hello World!|
|Hello World!|
+------------+
+---------------+
|こんちには|
|こんちには|
|こんちには|
|こんちには|
|こんちには|
+---------------+