Home > Java > javaTutorial > Java Design Patterns: Template Method Pattern Example Analysis

Java Design Patterns: Template Method Pattern Example Analysis

WBOY
Release: 2023-04-23 16:07:07
forward
1044 people have browsed it

Template Method Pattern

Template Method Pattern (Template Method) defines the algorithm skeleton in an operation and delays some steps of the algorithm to the subclass so that the subclass can Redefine certain specific steps of the algorithm without changing the structure of the algorithm.

The template method pattern contains the following main roles:

  • Abstract Class (Abstract Class): Responsible for giving an algorithm silhouette and skeleton. It consists of a template method and several basic methods.

    • Abstract method (Abstract Method): An abstract method is declared by an abstract class and implemented by its concrete subclass.

    • Concrete Method (Concrete Method): A concrete method is declared and implemented by an abstract class or concrete class, and its subclasses can override or inherit directly.

    • Hook method (Hook Method): It has been implemented in the abstract class, including logical methods for judgment and empty methods that need to be rewritten by subclasses. . The general hook method is a logical method used for judgment. The name of this method is generally isXxx, and the return value type is boolean.

    • Template method: defines the skeleton of the algorithm and calls the basic methods it contains in a certain order.

    • Basic method: It is the method to implement each step of the algorithm. Basic methods can be divided into three types:

  • Concrete subclass (Concrete Class): implements the abstract methods and hook methods defined in the abstract class , they are the constituent steps of a top-level logic.

##[Case]

The steps for cooking are fixed, including pouring oil, hot oil, pouring vegetables, pouring seasonings, and turning. Stir-fry and other steps. But you can throw in different vegetables and different sauces. Now use the template method mode to simulate it with code

Java Design Patterns: Template Method Pattern Example Analysis

public class TemplateTest {
    public static void main(String[] args) {
        //炒包菜
        BaoCai baoCai = new BaoCai();
        baoCai.cookProcess();
        System.out.println("-------------");
        //炒白菜
        BaiCai baiCai = new BaiCai();
        baiCai.cookProcess();
    }
}
abstract class AbstractClass{ //抽象类
    //模板方法定义
    public final void cookProcess() {
        this.pourOil();//倒油
        this.heatOil();//热油
        this.pourVegetable();//倒蔬菜
        this.pourSauce();//倒调味料
        this.fry();//翻炒
    }
    public abstract void pourVegetable();//倒蔬菜是不一样的(一个下包菜,一个是下白菜)
    public abstract void pourSauce();//倒调味料是不一样
    public void pourOil() {System.out.println("倒油");}
    public void heatOil() {System.out.println("热油");}
    public void fry(){System.out.println("炒啊炒");}
}
class BaoCai extends AbstractClass{
    public void pourVegetable() {System.out.println("加入包菜");}
    public void pourSauce() {System.out.println("加入辣椒酱");}
}
class BaiCai extends AbstractClass{
    public void pourVegetable() {System.out.println("加入白菜");}
    public void pourSauce() {System.out.println("加入盐和味精");}
}
Copy after login

[Run result]

Pour oilHot oil
Add cabbage
Add chili sauce
Saute and stir-fry
-------------
Pour oil
Hot oil
Add cabbage
Add salt and MSG
Stir fry

Process finished with exit code 0

template method mode Advantages and Disadvantages

Advantages:

1. Improve code reusability, put the same part of the code in the abstract parent class, and put different code in in different subcategories.

2. Reverse control is realized. A parent class calls the operation of its subclass, and different behaviors are extended through the specific implementation of the subclass. Reverse control is realized and complies with the "opening and closing principle" .

Disadvantages:

1. Each different implementation needs to define a subclass, which will lead to an increase in the number of classes, a larger system, and a larger design. More abstract.

2. The abstract methods in the parent class are implemented by the subclass. The execution result of the subclass will affect the result of the parent class, which leads to a reverse control structure, which increases the difficulty of code reading.

Usage Scenarios

1. The overall steps of the algorithm are very fixed, but when individual parts are volatile, you can use the template method pattern to abstract the easily variable parts for subclasses. accomplish.

2. It is necessary to use the subclass to decide whether a certain step in the parent class algorithm is executed, so as to realize the reverse control of the subclass over the parent class.

The above is the detailed content of Java Design Patterns: Template Method Pattern Example Analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template