12 - template method mode

Problems in soybean milk production

Prepare the procedure for making soybean milk, which is described as follows:
● 1) process of making soybean milk material selection ----- > adding ingredients ----- > soaking ----- > smashing in soybean milk machine
● 2) different flavors of soymilk can be produced by adding different ingredients
● 3) the steps of material selection, soaking and smashing in the soybean milk machine are the same for making each flavor of soybean milk
● 4) please use the template method mode to complete

Basic introduction

● 1) Template Method Pattern, also known as Template Pattern, defines the template of the method executing it in an abstract class. Its subclasses can override the method implementation as needed, but the call will be made in the way defined in the abstract class
● 2) in short, the template method pattern defines the skeleton of an algorithm in operation, and delays some steps to the subclass, so that the subclass can redefine some specific steps of the algorithm without changing the structure of an algorithm
● 3) this type of design mode belongs to behavioral mode

Schematic class diagram

Description of the schematic class diagram -- that is, the roles and responsibilities of the template method pattern
● AbstractClass abstract class implements the template method and defines the skeleton of the algorithm. Specific subclasses need to implement their abstract methods or rewrite their methods
● ConcreteClass implements the abstract method and has completed the steps of special subclasses in the algorithm

Template mode to solve the problem of soybean milk production

Core code

/**
 * @ClassName SoyaMilk
 * @author: shouanzh
 * @Description SoyaMilk Abstract class represents soybean milk
 * @date 2022/1/24 21:20
 */
public abstract class SoyaMilk {

    // Template methods do not allow subclasses to override
    public final void make() {
        System.out.println(">>>>>>Start of soybean milk production<<<<<<");
        useSoyBean();
        addIngredients();
        soak();
        mash();
        System.out.println(">>>>>>End of soybean milk production<<<<<<");
    }

    protected void useSoyBean() {
        System.out.println("Step1. Choose good soybeans.");
    }

    // Add different ingredient subclasses for specific implementation
    protected abstract void addIngredients();

    protected void soak() {
        System.out.println("Step3. Wash and soak soybeans and ingredients.");
    }

    protected void mash() {
        System.out.println("Step4. Put the fully soaked soybeans and ingredients into the soymilk machine and start beating soymilk.");
    }

}

/**
 * @ClassName RedBeanSoyaMilk
 * @author: shouanzh
 * @Description RedBeanSoyaMilk
 * @date 2022/1/24 21:31
 */
public class RedBeanSoyaMilk extends SoyaMilk{

    public RedBeanSoyaMilk() {
        System.out.println("============Red bean milk============");
    }

    @Override
    protected void addIngredients() {
        System.out.println("Step2. Add good red beans.");
    }
}

/**
 * @ClassName PeanutSoyaMilk
 * @author: shouanzh
 * @Description PeanutSoyaMilk
 * @date 2022/1/24 21:32
 */
public class PeanutSoyaMilk extends SoyaMilk{

    public PeanutSoyaMilk() {
        System.out.println("============Peanut soybean milk============");
    }

    @Override
    protected void addIngredients() {
        System.out.println("Step2. Add good peanuts.");
    }
}

/**
 * @ClassName Client
 * @author: shouanzh
 * @Description Client
 * @date 2022/1/24 21:33
 */
public class Client {

    public static void main(String[] args) {

        SoyaMilk redBeanSoyaMilk = new RedBeanSoyaMilk();
        redBeanSoyaMilk.make();

        SoyaMilk peanutSoyaMilk = new PeanutSoyaMilk();
        peanutSoyaMilk.make();

    }

}


Hook Method

● 1) in the parent class of the template method pattern, we can define a method that does nothing by default, and the subclass can override it according to the situation. This method is called "hook"
● 2) use the above example of making soybean milk to explain. For example, we also want to make pure soybean milk without adding any ingredients. Please use the hook method to transform the previous template method

Core code

/**
 * @ClassName SoyaMilk
 * @author: shouanzh
 * @Description SoyaMilk Abstract class represents soybean milk
 * @date 2022/1/24 21:20
 */
public abstract class SoyaMilk {

    // Template methods do not allow subclasses to override
    public final void make() {
        System.out.println(">>>>>>Start of soybean milk production<<<<<<");
        useSoyBean();
        if (customerWantCondiments()) {
            addIngredients();
        }
        soak();
        mash();
        System.out.println(">>>>>>End of soybean milk production<<<<<<");
    }

    protected void useSoyBean() {
        System.out.println("Step1. Choose good soybeans.");
    }

    // Add different ingredient subclasses for specific implementation
    protected abstract void addIngredients();

    protected void soak() {
        System.out.println("Step3. Wash and soak soybeans and ingredients.");
    }

    protected void mash() {
        System.out.println("Step4. Put the fully soaked soybeans and ingredients into the soymilk machine and start beating soymilk.");
    }

    // Hook Method 
    Boolean customerWantCondiments() {
        return true;
    }

}

/**
 * @ClassName PureSoyaMilk
 * @author: shouanzh
 * @Description Pure soybean milk
 * @date 2022/1/24 21:47
 */
public class PureSoyaMilk extends SoyaMilk{
    public PureSoyaMilk() {
        System.out.println("-----Pure soybean milk-------");
    }

    // Empty implementation
    @Override
    protected void addIngredients() {

    }

    @Override
    Boolean customerWantCondiments() {
        return false;
    }
}

/**
 * @ClassName Client
 * @author: shouanzh
 * @Description Client
 * @date 2022/1/24 21:33
 */
public class Client {

    public static void main(String[] args) {
        // Pure soybean milk
        SoyaMilk pureSoyaMilk = new PureSoyaMilk();
        pureSoyaMilk.make();

        // -----Pure soybean milk-------
        // >>>>>>Start of soybean milk production<<<<<<
        // Step1.  Choose good soybeans
        // Step3.  Wash and soak soybeans and ingredients
        // Step4.  Put the fully soaked soybeans and ingredients into the soymilk machine and start beating soymilk
        // >>>>>>End of soybean milk production<<<<<<
    }

}


Precautions and details

● 1) basic idea: the algorithm only exists in one place, that is, in the parent class, which is easy to modify. When the algorithm needs to be modified, as long as the template method of the parent class or some steps that have been implemented are modified, the child class will inherit these modifications
● 2) maximize code reuse. The template methods of the parent class and some implemented steps will be inherited by the child class and used directly
● 3) it not only unifies the algorithm, but also provides great flexibility. The template method of the parent class ensures that the structure of the algorithm remains unchanged, and the implementation of some steps is provided by the child class
● 4) shortcomings: each different implementation requires a subclass implementation, which increases the number of classes and makes the system more huge
● 5) general template methods are added with the final keyword to prevent subclasses from rewriting template methods
● 6) usage scenario: when a process is to be completed, it needs to execute a series of steps. These steps are basically the same, but their individual steps may be different in implementation. Template method mode is usually considered

Keywords: Java Design Pattern

Added by lalloo on Wed, 26 Jan 2022 02:33:31 +0200