Design Patterns 03 - Template Method pattern

definition

Template Method ( Template Method) mode is the mode with the templates, the template method of the composition of the method are defined in the parent class, these methods are abstract methods, a predetermined flow of execution of these methods in the template method, these methods require abstract subclass Implementation. In other words, the template is to define a good template, which is a certain process, as to the specific implementation of each abstract method, there is a subclass of their own decisions, so to see the parent class code is not aware of these methods will ultimately be what specific treatment is the only one who knows how to call the parent class of these methods.

These abstract methods to achieve the above subclass, implements the abstract method also determines the specific processing in the subclass. In other words, to achieve sub-class is no different in that when the template parent class is called, the manner is different, but it is worth mentioning that, no matter how abstract subclass method, how to customize defines its own processing logic, it calls the template method of the parent class when the parent class are specified in advance in accordance with good process to call these methods, respectively. Like this 在父类中定义好处理流程的框架,在子类中实现具体处理model is the template method ( Template Method) mode.

Issues into

In life you can often see cases similar to the Template Method pattern. For example, we have practiced childhood copybook, as long as we can copy a pen on a copybook beautiful words out and saw copybook, before copying can be sure we will write those words come out, but the written word effect you have to rely on the type of pen, brush can copy using a bold font, use the pen can copy a small font.

In the example, when cooking, the general steps are: 往锅里倒油——打开天然气灶——加入具体蔬菜——加入具体调料——出锅, then the process steps is a template, we follow this process can fry a hot vegetable, as vegetables and spices are added to what type, then you have to according to their own tastes.

Also, we usually play games have a specific step: 初始化游戏——开始玩游戏——游戏结束As for what kind of game play, you can choose according to their preferences, but this game will follow the steps. This step of the method the template is a template corresponding mode. The sample code will later be described in conjunction with the issue of the template model designed.

Application Template Method design pattern in the JDK source code

One template method pattern is a very common design patterns in JDKthe source code, there is a lot of shadow Template Method design pattern, such as:

  • java.io.InputStream, java.io.OutputStream, java.io.ReaderAs well as java.io.Writerall non-abstract methods.
  • java.util.AbstractList, java.util.AbstractSetAs well as java.util.AbstractMapall non-abstract methods.

Next, we take a reading java.io.InputStreamof the source code part, to feel the Template Method design pattern is how the JDKapplication. Here are java.io.InputStreama non-abstract abstract method and a method in which a non-abstract method is an important role template design mode - template.

public int read(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }

        int c = read();
        if (c == -1) {
            return -1;
        }
        b[off] = (byte)c;

        int i = 1;
        try {
            for (; i < len ; i++) {
                c = read();
                if (c == -1) {
                    break;
                }
                b[off + i] = (byte)c;
            }
        } catch (IOException ee) {
        }
        return i;
    }

public abstract int read() throws IOException;

Non-abstract methods given above the specific process of reading data from the input stream, and how to read from the input stream, but no specific method is given, need java.io.InputStreamsubclasses of the abstract class be embodied read method.

Manual template model designed to achieve

Perhaps reading here, you do not have a clear understanding of the Template Method design pattern, it does not matter, then start from the most simple example to show the basic principles of usage and Template Method design pattern.
We chose the above problems introduced in "play the game", use code to implement specific template method design pattern. First, we need an abstract class, the abstract class has variable contents and immutable content, variable content is the abstract class has an abstract method, which requires subclasses to achieve it, different subclasses of its implementation is often different; immutable content is the abstract class has a non-abstract method, this method is often abstract is finalmodified to, it does not allow subclasses to override it, it is the template method, which provides for the implementation processes of the abstract method, that is, He said that when the subclass to call the template method, each abstract method implementations are different, but their order execution processes and is indeed consistent. This is the basic principle Template Method design pattern. Template Method design pattern we will design class diagram as follows:
Here Insert Picture Description

  • Abstract class Game
package cn.itlemon.design.pattern.chapter03.template.method;

/**
 * 模板方法设计模式主要抽象类
 *
 * @author jiangpingping
 * @date 2018/9/14 下午3:22
 */
public abstract class Game {

    /**
     * 初始化游戏
     */
    public abstract void initialize();

    /**
     * 开始游戏
     */
    public abstract void startPlay();

    /**
     * 结束游戏
     */
    public abstract void endPlay();

    /**
     * 模板方法:确定了游戏的流程
     */
    public final void playGame() {
        initialize();
        startPlay();
        endPlay();
    }
}

Observe the abstract class, which has a variable content initialize, startPlay, endPlaythree abstract methods, there is an immutable content playGame, wherein the content immutable playGamemethod of performing a predetermined sequence of three abstract the above method.

  • Subclass BasketBallGame
package cn.itlemon.design.pattern.chapter03.template.method;

/**
 * 篮球游戏?
 *
 * @author jiangpingping
 * @date 2018/9/14 下午3:27
 */
public class BasketBallGame extends Game {

    @Override
    public void initialize() {
        System.out.println("Basketball Game Initialized! Start playing.");
    }

    @Override
    public void startPlay() {
        System.out.println("Basketball Game Started. Enjoy the game!");
    }

    @Override
    public void endPlay() {
        System.out.println("Basketball Game Finished!");
    }
}
  • Subclass FootBallGame
package cn.itlemon.design.pattern.chapter03.template.method;

/**
 * 足球游戏⚽️
 *
 * @author jiangpingping
 * @date 2018/9/14 下午3:30
 */
public class FootBallGame extends Game {

    @Override
    public void initialize() {
        System.out.println("Football Game Initialized! Start playing.");
    }

    @Override
    public void startPlay() {
        System.out.println("Football Game Started. Enjoy the game!");
    }

    @Override
    public void endPlay() {
        System.out.println("Football Game Finished!");
    }
}

Both subclasses inherit Gamethis abstract class and override the three abstract methods, which confirms the positive definition of Template Method design pattern: 在父类中定义好处理流程的框架,在子类中实现具体处理.

  • Main test class
package cn.itlemon.design.pattern.chapter03.template.method;

/**
 * @author jiangpingping
 * @date 2018/9/14 下午3:32
 */
public class Main {

    public static void main(String[] args) {
        Game basketBallGame = new BasketBallGame();
        Game footBallGame = new FootBallGame();
        basketBallGame.playGame();
        System.out.println();
        footBallGame.playGame();
    }
}

In this test class, we are creating two subclasses of objects and stored in the variable in the parent class of these two objects, when calling each playGametime methods, and we expect the same wish, in the specified order three variable methods were called, but the specific implementation of the different sub-classes is not the same.

Basketball Game Initialized! Start playing.
Basketball Game Started. Enjoy the game!
Basketball Game Finished!

Football Game Initialized! Start playing.
Football Game Started. Enjoy the game!
Football Game Finished!

On the Template Method pattern an important role

In the Template Method design pattern, only two main characters, namely: an abstract description of the method and template method of abstract class, and concrete subclasses implement abstract methods.

  • The AbstractClass (abstract)

AbstractClassThe main role is responsible for implementing the template method, and is also responsible for an abstract method declaration template method used in these abstract methods to be implemented by concrete subclasses, template method is responsible for calling the order of the abstract methods specified. In this example, the role of Gameplay to.

  • ConcreteClass (concrete class)

ConcreteClassRole is mainly responsible for implementing AbstractClassthe abstract role-declared, different ConcreteClassnot the same way these abstract methods, but due to the provisions of the calling sequence of these abstract methods in the parent class, all, even if the specific implementation is not the same, but the final order of execution is the same.

Template Method pattern UML Class Diagram

Template Design Method pattern UMLclass diagram is shown below:

Here Insert Picture Description

Why use a template method pattern

How to use the template method pattern can bring any benefit to our code? Its main advantage is to write in the parent class a good algorithm, no need to repeat writing in a subclass, if the algorithm has a problem, then you only need to modify the parent class template method can be.
It is also important that, when using the parent class types hold a subclass instance of an object, without the use of instanceofspecific types specified subclass, you can also call the template method directly.

More dry goods share, welcome attention to my micro-channel public number: Java Mountain (Micro Signal: itlemon)
Here Insert Picture Description

Published 73 original articles · won praise 84 · views 470 000 +

Guess you like

Origin blog.csdn.net/Lammonpeter/article/details/82694199