Skip to content

Instantly share code, notes, and snippets.

@shoheiyokoyama
Last active November 6, 2016 07:16
Show Gist options
  • Save shoheiyokoyama/2dac02bfba78751be1a6 to your computer and use it in GitHub Desktop.
Save shoheiyokoyama/2dac02bfba78751be1a6 to your computer and use it in GitHub Desktop.
デザインパターン「Template Method」 ref: http://qiita.com/shoheiyokoyama/items/c2ce16b4f492cd014d50
public abstract class AbstractDisplay {
public abstract void open();
public abstract void print();
public abstract void close();
//Template Method
public final void display() {
open();
for (int i =0; i < 3; i++) {
print();
}
close();
}
}
public class CharDisplay extends AbstractDisplay {
private char ch;
public CharDisplay(char ch) {
this.ch = ch;
}
public void open() {
System.out.print("***");
}
public void print() {
System.out.print(ch);
}
public void close() {
System.out.println("***");
}
}
***TTT***
+--------------+
|Design Pattern|
|Design Pattern|
|Design Pattern|
+--------------+
+---------------+
|Template Method|
|Template Method|
|Template Method|
+---------------+
public static void main(String[] args) {
//※
AbstractDisplay cd = new CharDisplay('T');
AbstractDisplay sd = new StringDisplay("Design Pattern");
AbstractDisplay sd2 = new StringDisplay("Template Method");
cd.display();
sd.display();
sd2.display();
}
public class StringDisplay extends AbstractDisplay {
private String string;
private int width;
public StringDisplay(String string) {
this.string = string;
this.width = string.getBytes().length;
}
public void open() {
printLine();
}
public void print() {
System.out.println("|" + string + "|");
}
public void close() {
printLine();
}
private void printLine() {
System.out.print("+");
for (int i = 0; i < width; i++) {
System.out.print("-");
}
System.out.println("+");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment