Design pattern--TemplateMethod pattern

Direct code:

public abstract class AbstractDisplay { // abstract class AbstractDisplay
    public abstract void open(); // abstract method to be implemented by subclasses (1) open
    public abstract void print(); // abstract method to be implemented by subclasses (2) print
    public abstract void close(); // abstract method to be implemented by subclasses (3) close
    public final void display() { // display method implemented in this abstract class
        open(); // first open...
        for (int i = 0; i < 5; i++) { // call print 5 times in a loop
            print();                    
        }
        close(); // ...finally closes. This is what the display method does
    }
}
public class CharDisplay extends AbstractDisplay { // CharDisplay is a subclass of AbstractDisplay
    private char ch; // characters to be displayed
    public CharDisplay(char ch) { // The character received in the constructor is
        this.ch = ch; // store in field
    }
    public void open() { // It is an abstract method in the parent class, override the method here  
        System.out.print("<<"); // Display the start character "<<"
    }
    public void print() { // Override the print method as well. This method will be called repeatedly in display
        System.out.print(ch); // print the character stored in field ch
    }
    public void close() { // similarly override the close method
        System.out.println(">>"); // Display the end character ">>"
    }
}
 
 
public class StringDisplay extends AbstractDisplay { // StringDisplay is also a subclass of AbstractDisplay
    private String string; // String to be displayed
    private int width; // string length in bytes
    public StringDisplay(String string) { // The string received in the constructor is
        this.string = string; // store in field
        this.width = string.getBytes().length; // Also save the byte length of the string in the field for later use
    }
    public void open() { // Overridden open method
        printLine(); // Call the printLine method of this class to draw a line
    }
    public void print() { // print method
        System.out.println("|" + string + "|"); // Add "|" before and after the string stored in the field and display it
    }
    public void close() {                               // close方法
        printLine(); // Same as the open method, call the printLine method to draw a line
    }
    private void printLine() { // Called by open and close methods. Since visibility is private, it can only be called within this class
        System.out.print("+"); // display the "+" representing the corner of the box
        for (int i = 0; i < width; i++) {               // 显示width个"-"
            System.out.print("-"); // Make up the border of the box
        }
        System.out.println("+"); // /Display "+" representing the corner of the box
    }
}
public class Main {
    public static void main(String[] args) {
        AbstractDisplay d1 = new CharDisplay('H'); // generate an instance of the CharDisplay class holding 'H'
        AbstractDisplay d2 = new StringDisplay("Hello, world."); // Generate an instance of StringDisplay class holding "Hello, world."
        AbstractDisplay d3 = new StringDisplay("Hello, world."); // Generate an instance of the StringDisplay class holding "Hello, world."
        d1.display(); // Since d1, d2 and d3 are all subclasses of AbstractDisplay
        d2.display(); // can call the inherited display method
        d3.display(); // Actual program behavior depends on the implementation of CharDisplay and StringDisplay
    }
}
The template method pattern is a code reuse technology based on inheritance . It embodies many important ideas of object-oriented and is a frequently used pattern. The template method pattern is widely used in framework design to ensure that the logical order of the processing flow (such as framework initialization, test flow setup, etc.) is controlled by the parent class.

 

       5-1 Mode Advantages

       The main advantages of the Template Method pattern are as follows:

       (1)  Formally define an algorithm in the parent class, and its subclasses implement the detailed processing. When the subclass implements the detailed processing algorithm, the execution order of the steps in the algorithm will not be changed.

       (2)  The template method pattern is a code reuse technology, which is particularly important in the design of class libraries. It extracts the common behaviors in the class library, puts the common behaviors in the parent class, and implements different behaviors through its subclasses. behavior, which encourages us to use inheritance appropriately for code reuse.

       (3)  A reverse control structure can be realized, and whether a specific step needs to be executed is determined by subclass overriding the hook method of the parent class.

       (4)  In the template method mode, subclasses can be used to override the basic methods of the parent class. Different subclasses can provide different implementations of the basic methods. It is very convenient to replace and add new subclasses, which conforms to the principle of single responsibility and the principle of opening and closing. .

 

       5-2 Mode Disadvantages

       The main disadvantages of the template method pattern are as follows:

       It is necessary to provide a subclass for different implementations of each basic method. If there are too many variable basic methods in the parent class, the number of classes will increase, the system will be larger, and the design will be more abstract. At this time, bridging can be combined. pattern to design.

 

       5-3 Mode Applicable Scenarios

       The template method pattern can be considered in the following situations:

       (1)  Divide some complex algorithms, design the fixed parts of the algorithm as template methods and specific methods of the parent class, and some details that can be changed are implemented by its subclasses. That is: implement the invariant parts of an algorithm once and leave the mutable behavior to subclasses.

       (2)  Common behaviors in each subclass should be extracted and concentrated into a common parent class to avoid code duplication.

       (3)  It is necessary to determine whether a step in the parent class algorithm is executed through the subclass, so as to realize the reverse control of the subclass to the parent class.





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325447548&siteId=291194637