Detailed explanation of template method pattern (template method design pattern)

Reference address

AQS defines abstract methods, which are useful in subclass implementation to template method design patterns

Preface

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, or the implementation of some steps is related to the specific environment.

For example, to go to a bank to handle business generally needs to go through the following four processes: taking number, queuing, handling specific business, scoring the bank staff, etc. the business of taking number, queuing and scoring the bank staff is the same for each customer, which can be realized in the parent class, but the specific business is different for each person, which may be deposit, withdrawal or transfer, etc , which can be implemented in a subclass.

There are many other examples in life, for example, a person will get up, eat, do things, sleep, etc. the content of "doing things" may be different every day. We define these instances with specified processes or formats as templates, allowing users to update them according to their own needs, such as resume templates, paper templates, template files in Word, etc.

The template method pattern described below will solve similar problems above.

Definition and characteristics of patterns

The definition of Template Method mode is 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 specific steps of the algorithm without changing the structure of the algorithm. It is a kind of behavioral model.

The main advantages of this mode are as follows.

  1. It encapsulates the invariant part and extends the mutable part. It encapsulates the algorithm which is regarded as the invariant part into the parent class, and inherits the variable part algorithm from the child class, so that the child class can continue to expand.
  2. It extracts the common part of the code in the parent class, which is convenient for code reuse.
  3. Part of the methods are implemented by subclasses, so subclasses can add corresponding functions through extension, which conforms to the open close principle.

The main disadvantages of this model are as follows.

  1. Each different implementation needs to define a subclass, which will lead to the increase of the number of classes, the system is more large, and the design is more abstract.
  2. Abstract methods in the parent class are implemented by subclasses, and the results of subclass execution will affect the results of the parent class, which leads to a reverse control structure, which improves the difficulty of code reading.

Structure and implementation of pattern

Template method pattern needs to pay attention to the cooperation between abstract classes and concrete subclasses. It uses the polymorphism technology of virtual function and the reverse control technology of "don't call me, let me call you". Now let's talk about their basic structure

1. Structure of mode

(1) Abstract Class: responsible for giving the outline and skeleton of an algorithm. It consists of a template method and several basic methods. These methods are defined 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 a concrete subclass.
  • Concrete method: it has been implemented in abstract class and can be inherited or overridden in concrete subclass.
  • Hook method: it has been implemented in abstract classes, including logical methods for judgment and empty methods that need to be rewritten by subclasses.

(2) Concrete Class: implements the abstract methods and hook methods defined in the abstract class, which are a component step of a top-level logic.

The structure diagram of the template method pattern is shown in Figure 1.

Figure 1 Structure of template method pattern

2. Implementation of the pattern

The code of the template method pattern is as follows:

package templateMethod;
public class TemplateMethodPattern
{
    public static void main(String[] args)
    {
        AbstractClass tm=new ConcreteClass();
        tm.TemplateMethod();
    }
}
//abstract class
abstract class AbstractClass
{
    public void TemplateMethod() //Template method
    {
        SpecificMethod();
        abstractMethod1();          
         abstractMethod2();
    }  
    public void SpecificMethod() //Specific methods
    {
        System.out.println("Concrete methods in abstract classes are called...");
    }   
    public abstract void abstractMethod1(); //Abstract method 1
    public abstract void abstractMethod2(); //Abstract method 2
}
//Specific subclasses
class ConcreteClass extends AbstractClass
{
    public void abstractMethod1()
    {
        System.out.println("The implementation of abstract method 1 is called...");
    }   
    public void abstractMethod2()
    {
        System.out.println("The implementation of abstract method 2 is called...");
    }
}

The running results of the program are as follows:

Concrete methods in abstract classes are called
 The implementation of abstract method 1 is called
 The implementation of abstract method 2 is called

Application examples of patterns

[example 1] using the template method to realize the procedure design of studying abroad.

Analysis: the procedures for studying abroad generally go through the following processes: obtaining school information, applying for admission, handling passport, exit card and notarization for private purposes, applying for visa, physical examination, booking air tickets, preparing luggage, arriving at the target school, etc., some of which are the same for each school, but some of which are different due to different schools, so it is more suitable to use the template method mode To achieve.

In this example, we first define an abstract class StudyAbroad for studying abroad, which contains a template method TemplateMethod(), which contains various basic methods in the process of going through the formalities of studying abroad, some of which can be implemented in abstract classes because all countries are the same, but some of them are different in different countries and must be implemented in their specific subclass (such as StudyInAmerica). If you add another country, just add a subclass. Figure 2 shows its structure.

Figure 2 structure of procedure design for studying abroad

The program code is as follows:

package templateMethod;
public class StudyAbroadProcess
{
    public static void main(String[] args)
    {
        StudyAbroad tm=new StudyInAmerica();
        tm.TemplateMethod();
    }
}
//Abstract: studying abroad
abstract class StudyAbroad
{
    public void TemplateMethod() //Template method
    {
        LookingForSchool(); //Ask for school information
        ApplyForEnrol();    //Admission application      
        ApplyForPassport(); //Handle passport, exit card and notarization
        ApplyForVisa();     //Apply for a visa
        ReadyGoAbroad();    //Physical examination, air ticket booking and preparation for packing
        Arriving();         //Arrive
    }              
    public void ApplyForPassport()
    {
        System.out.println("Three.To handle passports, exit cards and notarization for private purposes:");
        System.out.println("  1)Apply to the local public security organ for the passport and exit card for personal reasons with the admission notice, my household register or ID card.");
        System.out.println("  2)Handle notarization of birth, education background, degree and achievement, experience certificate, kinship and economic guarantee.");
    }
    public void ApplyForVisa()
    {
        System.out.println("Four.apply for a visa:");
        System.out.println("  1)Prepare all kinds of materials required for applying for visa abroad, including personal education background, report card, work experience certificate, personal and family income, capital and property certificate, family member relationship certificate, etc;");
        System.out.println("  2)To the envoys of the countries to study in China(collar)The museum applies for an entry visa. When applying, you need to fill in the relevant forms as required, submit the necessary supporting materials and pay the visa. Some countries(Such as the United States, Britain, Canada, etc)When applying for a visa, the applicant will be required to go to the Embassy(collar)Interview in the library.");
    }
    public void ReadyGoAbroad()
    {
        System.out.println("Five.Physical examination, air ticket booking and preparation for packing:");
        System.out.println("  1)Carry out physical examination, immune examination and vaccination against infectious diseases;");
        System.out.println("  2)Determine the ticket time, flight and transfer location.");
    }
    public abstract void LookingForSchool();//Ask for school information
    public abstract void ApplyForEnrol();   //Admission application
    public abstract void Arriving();        //Arrive
}
//Specific subcategory: studying in the United States
class StudyInAmerica extends StudyAbroad
{
    @Override
    public void LookingForSchool()
    {
        System.out.println("One.Ask for the following information:");
        System.out.println("  1)To have a comprehensive understanding of the political, economic, cultural background, educational system and academic level of the countries that intend to study abroad;");
        System.out.println("  2)To fully understand and master the situation of foreign schools, including history, tuition, school system, major, teachers, teaching facilities, academic status, number of students, etc;");
        System.out.println("  3)Understand the accommodation, transportation and medical insurance of the school;");
        System.out.println("  4)Does the school have an authorized agency in China?");
        System.out.println("  5)Master the visa status of studying abroad;");
        System.out.println("  6)Does the government allow overseas students to work legally?");
        System.out.println("  8)Can I immigrate after graduation?");
        System.out.println("  9)Is the diploma recognized by China?");
    }
    @Override
    public void ApplyForEnrol()
    {
        System.out.println("Two.Application:");
        System.out.println("  1)Fill in the application form;");
        System.out.println("  2)Send the application form, personal education certificate, recent study report, recommendation letter, resume, TOEFL or IELTS language test report to the school;");
        System.out.println("  3)In order to leave enough time for visa application, it is suggested that the earlier the application is, the better. Generally, it is easier to apply one year in advance.");       
    }
    @Override
    public void Arriving()
    {
        System.out.println("Six.Arrival at target school:");
        System.out.println("  1)Arrange accommodation;");
        System.out.println("  2)Understand the campus and surrounding environment.");
    }
}

The running results of the program are as follows:

1, Ask for the following information:
  1) To have a comprehensive understanding of the political, economic, cultural background, educational system and academic level of the countries that intend to study abroad;
  2) To fully understand and master the situation of foreign schools, including history, tuition, school system, major, teachers, teaching facilities, academic status, number of students, etc;
  3) Understand the accommodation, transportation and medical insurance of the school;
  4) Does the school have an authorized agency in China?
  5) Master the visa status of studying abroad;
  6) Does the government allow overseas students to work legally?
  8) Can I immigrate after graduation?
  9) Is the diploma recognized by China?
2, Application:
  1) Fill in the application form;
  2) Send the application form, personal education certificate, recent study report, recommendation letter, resume, TOEFL or IELTS language test report to the school;
  3) In order to leave enough time for visa application, it is suggested that the earlier the application is, the better. Generally, it is easier to apply one year in advance.
3, To handle passports, exit cards and notarization for private purposes:
  1) Apply to the local public security organ for the passport and exit card for personal reasons with the admission notice, my household register or ID card.
  2) Handle notarization of birth, education background, degree and achievement, experience certificate, kinship and economic guarantee.
4, Visa application:
  1) Prepare all kinds of materials required for applying for visa abroad, including personal education background, report card, work experience certificate, personal and family income, capital and property certificate, family member relationship certificate, etc;
  2) Apply for an entry visa to the embassy (consulate) of the country to study in China. When applying, you need to fill in the relevant forms as required, submit the necessary supporting materials and pay the visa. Some countries (such as the United States, the United Kingdom, Canada, etc.) require applicants to go to the embassy (consulate) for an interview when applying for a visa.
5, Physical examination, air ticket booking and preparation for packing:
  1) Carry out physical examination, immune examination and vaccination against infectious diseases;
  2) Determine the ticket time, flight and transfer location.
6, Arrival at target school:
  1) Arrange accommodation;
  2) Understand the campus and surrounding environment.

Application scenario of pattern

The template method pattern is generally applicable to the following scenarios.

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

Pattern extension

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

Figure 3 structure of template method pattern with hook method

The program code is as follows:

package templateMethod;
public class HookTemplateMethod
{
    public static void main(String[] args)
    {
        HookAbstractClass tm=new HookConcreteClass();
        tm.TemplateMethod();
    }
}
//Abstract class with hook method
abstract class HookAbstractClass
{
    public void TemplateMethod() //Template method
    {
        abstractMethod1();
        HookMethod1();
        if(HookMethod2())
        {
            SpecificMethod();   
        }
         abstractMethod2();
    }  
    public void SpecificMethod() //Specific methods
    {
        System.out.println("Concrete methods in abstract classes are called...");
    }
    public void HookMethod1(){}  //Hook method 1
    public boolean HookMethod2() //Hook method 2
    {
        return true;
    }
    public abstract void abstractMethod1(); //Abstract method 1
    public abstract void abstractMethod2(); //Abstract method 2
}
//Concrete subclass with hook method
class HookConcreteClass extends HookAbstractClass
{
    public void abstractMethod1()
    {
        System.out.println("The implementation of abstract method 1 is called...");
    }   
    public void abstractMethod2()
    {
        System.out.println("The implementation of abstract method 2 is called...");
    }   
    public void HookMethod1()
    {
        System.out.println("Hook method 1 overridden...");
    }
    public boolean HookMethod2()
    {
        return false;
    }
}

The running results of the program are as follows:

The implementation of abstract method 1 is called
 Hook method 1 overridden
 The implementation of abstract method 2 is called

If the code of hook method HookMethod1() and hook method HookMethod2() changes, the running result of the program will also change.

75 original articles published, 48 praised, 350000 visitors+
Private letter follow

Tags: Programming

Posted on Fri, 13 Mar 2020 03:35:46 -0700 by mbariou