1
2
3
4
5 abstract class AbstractDisplay {
6 public abstract void open();
7 public abstract void print();
8 public abstract void close();
9 public final void display() {
10 open();
11 for(int i=0; i<5; i++) print();
12 close();
13 }
14 }
15
16 class CharDisplay extends AbstractDisplay {
17 private char ch;
18 public CharDisplay(char ch) {
19 this.ch = ch;
20 }
21 public void open() {
22 System.out.print("<<");
23 }
24 public void print() {
25 System.out.print(ch);
26 }
27 public void close() {
28 System.out.println(">>");
29 }
30 }
31
32 class StringDisplay extends AbstractDisplay {
33 private String string;
34 private int width;
35 public StringDisplay(String string) {
36 this.string = string;
37 this.width = string.getBytes().length;
38 }
39 public void open() {
40 printLine();
41 }
42 public void print() {
43 System.out.println("|"+string+"|");
44 }
45 public void close() {
46 printLine();
47 }
48 private void printLine() {
49 System.out.print("+");
50 for(int i=0; i<width; i++) {
51 System.out.print("-");
52 }
53 System.out.println("+");
54 }
55 }
56
57 public class TemplateMethodDisplay {
58 public static void main(String[] args) {
59 AbstractDisplay d1 = new CharDisplay('H');
60 AbstractDisplay d2 = new StringDisplay("Hello world");
61 d1.display();
62 d2.display();
63 }
64 }