Design Pattern-Template Method Design Pattern

1 Introduction

In the process of object-oriented programming, programmers often encounter this situation: when designing a system, they know the key steps required by the algorithm, and determine the execution order of these steps, but the specific implementation of some steps is still unknown. In other words, the realization of certain steps is related to the specific environment.

For example, going to a bank to handle business generally involves the following four processes: taking number, queuing, handling specific business, scoring bank staff, etc. The business of taking number, queuing and scoring bank staff is for each customer The same can be implemented in the parent class, but the specific business handled varies from person to person. It may be deposit, withdrawal or transfer, etc., which can be delayed to the subclass.

There are many such examples in life. For example, a person gets up, eats, does things, and sleeps every day, and the content of "doing things" may be different every day. We define these examples of processes or formats as templates, and allow users to update them according to their own needs, such as resume templates, paper templates, and template files in Word.

The template method mode introduced below will solve the above similar problems

2. The definition and characteristics of the model

The template method (Template Method) mode is defined as follows: define the algorithm skeleton in an operation, and delay some steps of the algorithm to the subclass, so that the subclass can redefine some of the algorithm without changing the structure of the algorithm Specific steps. It is a kind of behavioral pattern.

The main advantages of this mode are as follows:

  1. It encapsulates the invariant part and expands the variable part. It encapsulates the algorithm that is considered to be the invariant part into the parent class and implements the variable part algorithm by inheritance from the subclass to facilitate the continued expansion of the subclass.
  2. It extracts the common part of the code in the parent class to facilitate code reuse.
  3. Some methods are implemented by subclasses, so subclasses can add corresponding functions through extensions, which conform to the principle of opening and closing.

The main disadvantages of this model are as follows:

  1. For each different implementation, you need to define a subclass, which will increase the number of classes, make the system larger, and the design more abstract, which indirectly increases the complexity of the system implementation.
  2. The abstract method in the parent class is implemented by the subclass, and the result of the execution 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.
  3. Due to the shortcomings of the inheritance relationship, if the parent class adds a new abstract method, all subclasses must be changed again.

3. The structure and realization of the pattern

The template method pattern requires attention to the collaboration between abstract classes and concrete subclasses. It uses the polymorphism technology of virtual functions and the reverse control technology of "don't call me, let me call you". Now let’s introduce their basic structure.

1. The structure of the model

The template method pattern contains the following main roles.

1) Abstract class/abstract template (Abstract Class)

The abstract template class is responsible for giving the outline and skeleton of an algorithm. It consists of a template method and several basic methods. The definitions of these methods are as follows.

① Template method: defines the skeleton of the algorithm, and calls the basic methods contained in it in a certain order.
② Basic method: It is a step in the whole algorithm, including the following types.

  • Abstract method: declared in an abstract class and implemented by concrete subclasses.
  • Concrete method: It has been implemented in the abstract class, and it can be inherited or rewritten in the concrete subclass.
  • Hook method: Has been implemented in the abstract class, including two types of logical methods for judgment and empty methods that need to be rewritten by subclasses.

2) Concrete Subclass/Concrete Class

The concrete realization class implements the abstract methods and hook methods defined in the abstract class. They are a constituent step of a top-level logic.

Insert picture description here

2. Implementation of the pattern

public class TemplateMethodPattern {
    
    
    public static void main(String[] args) {
    
    
        AbstractClass tm = new ConcreteClass();
        tm.TemplateMethod();
    }
}

//抽象类
abstract class AbstractClass {
    
    
    //模板方法
    public void TemplateMethod() {
    
    
        SpecificMethod();
        abstractMethod1();
        abstractMethod2();
    }

    //具体方法
    public void SpecificMethod() {
    
    
        System.out.println("抽象类中的具体方法被调用...");
    }

    //抽象方法1
    public abstract void abstractMethod1();

    //抽象方法2
    public abstract void abstractMethod2();
}

//具体子类
class ConcreteClass extends AbstractClass {
    
    
    public void abstractMethod1() {
    
    
        System.out.println("抽象方法1的实现被调用...");
    }

    public void abstractMethod2() {
    
    
        System.out.println("抽象方法2的实现被调用...");
    }
}

The concrete method in the abstract class is called...
The implementation of abstract method 1 is called...
The implementation of abstract method 2 is called...

3. Application examples of the pattern

[Example 1] Use the template method model to realize the design procedure of studying abroad procedures.

Analysis: The procedures for studying abroad generally go through the following processes: requesting school information, submitting an application for admission, handling passports, exit cards and notarizations for private trips, applying for visas, physical examinations, booking air tickets, preparing luggage, arriving at the target school, etc. The schools are the same, but some businesses are different from school to school, so it is more suitable to use the template method model to achieve.

In this example, we first define an abstract class StudyAbroad for studying abroad, which contains a template method TemplateMethod(), which contains all the basic methods in the process of going through the procedures for studying abroad. Some of the methods are handled by different countries. The same, so it can be implemented in abstract classes, but some methods are different in different countries and must be implemented in their specific subclasses (such as StudyInAmerica in the United States). If you add another country, you only need to add a sub-category. Figure 2 shows its structure.

Insert picture description here

public class StudyAbroadProcess {
    
    
    public static void main(String[] args) {
    
    
        StudyAbroad tm = new StudyInAmerica();
        tm.TemplateMethod();
    }
}

//抽象类: 出国留学
abstract class StudyAbroad {
    
    
    public void TemplateMethod() //模板方法
    {
    
    
        LookingForSchool(); //索取学校资料
        ApplyForEnrol();    //入学申请
        ApplyForPassport(); //办理因私出国护照、出境卡和公证
        ApplyForVisa();     //申请签证
        ReadyGoAbroad();    //体检、订机票、准备行装
        Arriving();         //抵达
    }

    public void ApplyForPassport() {
    
    
        System.out.println("三.办理因私出国护照、出境卡和公证:");
        System.out.println("  1)持录取通知书、本人户口簿或身份证向户口所在地公安机关申请办理因私出国护照和出境卡。");
        System.out.println("  2)办理出生公证书,学历、学位和成绩公证,经历证书,亲属关系公证,经济担保公证。");
    }

    public void ApplyForVisa() {
    
    
        System.out.println("四.申请签证:");
        System.out.println("  1)准备申请国外境签证所需的各种资料,包括个人学历、成绩单、工作经历的证明;个人及家庭收入、资金和财产证明;家庭成员的关系证明等;");
        System.out.println("  2)向拟留学国家驻华使(领)馆申请入境签证。申请时需按要求填写有关表格,递交必需的证明材料,缴纳签证。有的国家(比如美国、英国、加拿大等)在申请签证时会要求申请人前往使(领)馆进行面试。");
    }

    public void ReadyGoAbroad() {
    
    
        System.out.println("五.体检、订机票、准备行装:");
        System.out.println("  1)进行身体检查、免疫检查和接种传染病疫苗;");
        System.out.println("  2)确定机票时间、航班和转机地点。");
    }

    public abstract void LookingForSchool();//索取学校资料

    public abstract void ApplyForEnrol();   //入学申请

    public abstract void Arriving();        //抵达
}

//具体子类: 美国留学
class StudyInAmerica extends StudyAbroad {
    
    
    @Override
    public void LookingForSchool() {
    
    
        System.out.println("一.索取学校以下资料:");
        System.out.println("  1)对留学意向国家的政治、经济、文化背景和教育体制、学术水平进行较为全面的了解;");
        System.out.println("  2)全面了解和掌握国外学校的情况,包括历史、学费、学制、专业、师资配备、教学设施、学术地位、学生人数等;");
        System.out.println("  3)了解该学校的住宿、交通、医疗保险情况如何;");
        System.out.println("  4)该学校在中国是否有授权代理招生的留学中介公司?");
        System.out.println("  5)掌握留学签证情况;");
        System.out.println("  6)该国政府是否允许留学生合法打工?");
        System.out.println("  8)毕业之后可否移民?");
        System.out.println("  9)文凭是否受到我国认可?");
    }

    @Override
    public void ApplyForEnrol() {
    
    
        System.out.println("二.入学申请:");
        System.out.println("  1)填写报名表;");
        System.out.println("  2)将报名表、个人学历证明、最近的学习成绩单、推荐信、个人简历、托福或雅思语言考试成绩单等资料寄往所申请的学校;");
        System.out.println("  3)为了给签证办理留有充裕的时间,建议越早申请越好,一般提前1年就比较从容。");
    }

    @Override
    public void Arriving() {
    
    
        System.out.println("六.抵达目标学校:");
        System.out.println("  1)安排住宿;");
        System.out.println("  2)了解校园及周边环境。");
    }
}

1. Obtain the following information from the school:
1) Have a more comprehensive understanding of the political, economic, cultural background, educational system and academic level of the country where you intend to study abroad;
2) Have a comprehensive understanding of and master the situation of foreign schools, including history, tuition, school system, Majors, faculty, teaching facilities, academic status, number of students, etc.;
3) Know the accommodation, transportation, and medical insurance of
the school ; 4) Does the school have an overseas study agency that is authorized to enroll students in China?
5) Know the status of student visa;
6) Does the government of the country allow international students to work legally?
8) Can I immigrate after graduation?
9) Is the diploma recognized by my country?
2. Admission application:
1) Fill in the registration form;
2) Send the registration form, personal academic certificate, recent academic transcripts, recommendation letters, resumes, TOEFL or IELTS language test transcripts and other materials to the school you applied for;
3 ) In order to allow plenty of time for visa processing, it is recommended to apply as soon as possible. Generally, it is more calm one year in advance.
3.
Apply for a private passport, exit card and notarization: 1) Apply for a private passport and exit card to the public security agency where your residence is registered with the admission notice, your household register or ID card.
2) Notarization of birth certificate, notarization of education, degree and grades, certificate of experience, notarization of kinship, and notarization of financial guarantee.
4. Applying for a visa:
1) Prepare all kinds of materials required to apply for a foreign visa, including proof of personal education, transcripts, work experience; proof of personal and family income, funds and property; proof of family members' relationship, etc.;
2) Apply for an entry visa to the embassy (consulate) of the country you intend to study in China. When applying, you need to fill in the relevant forms, submit the necessary supporting materials, and pay the visa as required. Some countries (such as the United States, the United Kingdom, Canada, etc.) require the applicant to go to the embassy (consulate) for an interview when applying for a visa.
V. Physical examination, booking air tickets, and preparing for packing:
1) Conduct physical examinations, immunization checks and vaccinations against infectious diseases;
2) Determine the time of air tickets, flights and transfer locations.
6. Arrive at the target school:
1) Arrange accommodation;
2) Understand the campus and surrounding environment.

4. Application scenarios of the mode

The template method pattern is usually suitable for the following scenarios

  1. The overall steps of the algorithm are very fixed, but when individual parts of them are changeable, the template method pattern can be used at this time to abstract the changeable parts for subclasses to implement.
  2. When multiple subclasses have common behaviors, they can be extracted and concentrated into a common parent class to avoid code duplication. First, identify the differences in the existing code and separate the differences into new operations. Finally, replace these different codes with a template method that calls these new operations.
  3. When you need to control the extension of subclasses, template methods only call hook operations at specific points, so that extensions are only allowed at these points.

5. Expansion of the model

In the template method pattern, the basic methods include: abstract methods, concrete methods, and hook methods. The correct use of "hook methods" can make the child class control the behavior of the parent class. As in the following example, you can change the running result in the abstract parent class by overriding the hook methods HookMethod1() and HookMethod2() in the concrete subclass. The structure diagram is shown in Figure 3.

Insert picture description here

public class HookTemplateMethod {
    
    
    public static void main(String[] args) {
    
    
        HookAbstractClass tm = new HookConcreteClass();
        tm.TemplateMethod();
    }
}

//含钩子方法的抽象类
abstract class HookAbstractClass {
    
    
    //模板方法
    public void TemplateMethod() {
    
    
        abstractMethod1();
        HookMethod1();
        if (HookMethod2()) {
    
    
            SpecificMethod();
        }
        abstractMethod2();
    }

    //具体方法
    public void SpecificMethod() {
    
    
        System.out.println("抽象类中的具体方法被调用...");
    }

    //钩子方法1
    public void HookMethod1() {
    
    
    }

    //钩子方法2
    public boolean HookMethod2() {
    
    
        return true;
    }

    //抽象方法1
    public abstract void abstractMethod1();

    //抽象方法2
    public abstract void abstractMethod2();
}

//含钩子方法的具体子类
class HookConcreteClass extends HookAbstractClass {
    
    
    public void abstractMethod1() {
    
    
        System.out.println("抽象方法1的实现被调用...");
    }

    public void abstractMethod2() {
    
    
        System.out.println("抽象方法2的实现被调用...");
    }

    public void HookMethod1() {
    
    
        System.out.println("钩子方法1被重写...");
    }

    public boolean HookMethod2() {
    
    
        return false;
    }
}

The implementation of abstract method 1 is called...
hook method 1 is rewritten...
the implementation of abstract method 2 is called...

Guess you like

Origin blog.csdn.net/saienenen/article/details/112652825