Template design pattern

  English name template template, in this mode, there is a major role in the AbstractClass (abstract) and ConcreteClass (concrete class), where for example the following;

  The display section of characters or strings cycle 5 times;

  First, the definition of an abstract class, an abstract class, the display method is the template by calling the subclass diaplay method, it will perform according to a method of fixing, the specific methods defined in the subclass which is performed, as follows:

 1 package t2020010602;
 2 
 3 public abstract class AbstractDisplay {
 4     public abstract void open();
 5 
 6     public abstract void print();
 7 
 8     public abstract void close();
 9 
10     public final void display() {
11         open();
12         for (int i = 0; i < 5; i++) {
13             print();
14         }
15         close();
16     }
17 }

Then define particular method subclass

 1 package t2020010602;
 2 
 3 public class CharDisplay extends AbstractDisplay {
 4     private char ch;
 5 
 6     public CharDisplay(char ch) {
 7         this.ch = ch;
 8     }
 9 
10     @Override
11     public void open() {
12         System.out.print("<<");
13     }
14 
15     @Override
16     public void print() {
17         System.out.print(ch);
18     }
19 
20     @Override
21     public void close() {
22         System.out.println(">>");
23     }
24 
25 }
 1 package t2020010602;
 2 
 3 public class StringDisplay extends AbstractDisplay {
 4     private String string;
 5 
 6     private int length;
 7 
 8     public StringDisplay(String string) {
 9         this.string = string;
10         length = string.getBytes().length;
11     }
12 
13     @Override
14     public void open() {
15         printLine();
16     }
17 
18     @Override
19     public void print() {
20         System.out.println("+" + string + "+");
21     }
22 
23     @Override
24     public void close() {
25         printLine();
26     }
27 
28     public void printLine() {
29         System.out.print("+");
30         for (int i = 0; i < length; i++) {
31             System.out.print("-");
32         }
33         System.out.println("+");
34     }
35 
36 }

As the program entry

 1 package t2020010602;
 2 
 3 public class Main {
 4 
 5     public static void main(String[] args) {
 6         AbstractDisplay d1 = new CharDisplay('H');
 7         AbstractDisplay d2 = new StringDisplay("Hello world;");
 8         d1.display();
 9         d2.display();
10     }
11 
12 }

You can see, d1 and d2 calls the same method, but perform a different approach body, this is the template program;

Guess you like

Origin www.cnblogs.com/xiaoyaomianbiren/p/12158522.html