Design pattern template method

Overview

The template method is to define the skeleton of an algorithm, and delay specific steps in the skeleton to subclasses. The template method pattern allows subclasses to redefine (rewrite) certain specific steps of the algorithm without changing the structure of the algorithm.

Pros and cons

advantage

  1. Solved the code duplication problem
  2. Improved code scalability
  3. Specifies the execution flow of the code

Disadvantage

  1. Every time an implementation is added, a subclass must be added

example

The greatness of China lies in its 5,000-year history and the birth of its own medical system. Today, people can choose Chinese medicine and Western medicine to see a doctor. The general process of going to the hospital for the two is the same, but the diagnosis methods are different. The code form is displayed.
Registration → diagnosis → payment → medicine

Abstract template

/**
 * @author yz
 * @version 1.0
 * @date 2020/10/21 11:34
 * 医院模板类
 */
public abstract class Hospital {
    
    

    //治疗
    public void medicalTreatment(){
    
    
        registered();
        diagnosis();
        pay();
        takeMedicine();
    }

    //挂号
    public final void registered(){
    
    
        System.out.println("挂号");
    }

    //诊断
    public abstract void diagnosis();

    //缴费
    public final void  pay(){
    
    
        System.out.println("缴费");
    }

    //取药
    public abstract void takeMedicine();

}

Implementation

/**
 * @author yz
 * @version 1.0
 * @date 2020/10/21 11:40
 * 中医院
 */
public class ChineseHospital extends Hospital{
    
    
    @Override
    public void diagnosis() {
    
    
        System.out.println("望闻问切");
    }

    @Override
    public void takeMedicine() {
    
    
        System.out.println("取中药");
    }
}
/**
 * @author yz
 * @version 1.0
 * @date 2020/10/21 11:40
 * 西医院
 */
public class WestHospital extends Hospital{
    
    
    @Override
    public void diagnosis() {
    
    
        System.out.println("化验单、检查单等");
    }

    @Override
    public void takeMedicine() {
    
    
        System.out.println("取西药");
    }
}

Test class

public static void main(String[] args) {
    
    
        Hospital westHospital=new WestHospital();
        westHospital.medicalTreatment();
        System.out.println("--------------------------");
        Hospital chineseHospital=new ChineseHospital();
        chineseHospital.medicalTreatment();
    }
挂号
化验单、检查单等
缴费
取西药
--------------------------
挂号
望闻问切
缴费
取中药

to sum up

The template method is a very common design pattern in design patterns. It is easy to learn and use. Generally speaking, it still relies on the principle of inversion. The program depends on abstract interfaces, not on specific implementations.

Guess you like

Origin blog.csdn.net/qq_38306425/article/details/109200377