Java design pattern-14-Template Method pattern

Posted by gillms1 on Wed, 26 Jan 2022 03:16:16 +0100

preface

Behavioral pattern is used to describe the complex process control of a program at run time, that is, how multiple classes or objects cooperate with each other to complete tasks that can not be completed by a single object. It involves the allocation of responsibilities between algorithms and objects.

Behavioral patterns are divided into class behavior patterns and object behavior patterns. The former uses inheritance mechanism to allocate behavior between classes, and the latter uses combination or aggregation to allocate behavior between objects. Because the coupling degree of composite relationship or aggregation relationship is lower than that of inheritance relationship and meets the "composite Reuse Principle", the object behavior pattern has more flexibility than the class behavior pattern.

Behavioral pattern is the largest category of GoF design patterns, which includes the following 11 patterns:

  1. Template Method mode: 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.
  2. Strategy pattern: it defines a series of algorithms and encapsulates each algorithm so that they can be replaced with each other, and the change of the algorithm will not affect the customers using the algorithm.
  3. Command mode: encapsulates a request as an object, separating the responsibility of issuing the request from the responsibility of executing the request.
  4. Chain of Responsibility mode: transfer the request from one object in the chain to the next until the request is responded. In this way, the coupling between objects is removed.
  5. State mode: allows an object to change its behavior when its internal state changes.
  6. Observer mode: there is a one to many relationship between multiple objects. When an object changes, it notifies other objects of the change, thereby affecting the behavior of other objects.
  7. Mediator mode: define a mediation object to simplify the interaction between the original objects, reduce the coupling between the objects in the system, and make it unnecessary for the original objects to understand each other.
  8. Iterator pattern: provides a way to sequentially access a series of data in an aggregate object without exposing the internal representation of the aggregate object.
  9. Visitor mode: provide multiple access methods for each element in a collection without changing the collection elements, that is, each element has multiple visitor objects to access.
  10. Memo mode: on the premise of not destroying encapsulation, obtain and save the internal state of an object for later recovery.
  11. Interpreter mode: it provides how to define the grammar of the language and the interpretation method of language sentences, that is, the interpreter.

Among the above 11 behavior modes, except that the template method mode and interpreter mode are class behavior modes, all others belong to object behavior modes,

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, when you go to a bank to handle business, you generally go through the following four processes: number taking, queuing, handling specific business, scoring bank staff, etc. among them, the business of number taking, queuing and scoring bank staff is the same for each customer and can be implemented in the parent class, but the specific business varies from person to person. It may be deposit, withdrawal or transfer, Implementation can be deferred to subclasses.

There are many such 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 that specify the process or format as templates, allowing users to update them according to their own needs, such as resume templates, thesis templates, template files in Word, etc.

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

Definition and characteristics of pattern

The definition of Template Method pattern 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.

advantage:

  • It encapsulates the invariant part and extends the variable part. It encapsulates the algorithm that is considered to be the invariant part into the parent class, and inherits the variable part algorithm from the subclass, which is convenient for the subclass to continue to expand.
  • It extracts part of the common code from the parent class to facilitate code reuse.
  • Some methods are implemented by subclasses, so subclasses can add corresponding functions through extension, which conforms to the opening and closing principle.

Disadvantages:

  • It is necessary to define a subclass for each different implementation, which will increase the number of classes, make the system larger and the design more abstract, and indirectly increase the complexity of the system implementation.
  • Abstract methods in the parent class are implemented by subclasses, and the execution results of subclasses will affect the results of the parent class, which leads to a reverse control structure, which improves the difficulty of code reading.
  • Due to the shortcomings of the inheritance relationship itself, if a new abstract method is added to the parent class, all subclasses must be changed again.

Structure and implementation of pattern

The template method pattern needs to pay attention to the cooperation 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. Structure of the model

The template method pattern contains the following main roles.

1) Abstract Class / Abstract Class

Abstract template class, which is 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 its basic methods 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 an abstract class and can be inherited or overridden in a 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

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

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

2. Implementation of mode

The code of template method mode is as follows:

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

//abstract class
abstract class AbstractClass {
    //Template method
    public void TemplateMethod() {
        SpecificMethod();
        abstractMethod1();
        abstractMethod2();
    }

    //Specific method
    public void SpecificMethod() {
        System.out.println("Concrete methods in abstract classes are called...");
    }

    //Abstract method 1
    public abstract void abstractMethod1();

    //Abstract method 2
    public abstract void abstractMethod2();
}

//Specific subclass
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 pattern

[example 1] use the template method mode to realize the study abroad procedure design program.

Analysis: the procedures for studying abroad generally go through the following processes: obtaining school materials, applying for admission, handling private passports, exit cards and notarization, applying for visas, physical examination, booking air tickets, preparing luggage, arriving at the target school, etc. some businesses are the same for each school, but some businesses are different for different schools, Therefore, it is more suitable to implement it with template method pattern.

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

The program code is as follows:

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

//Abstract: study abroad
abstract class StudyAbroad {
    public void TemplateMethod() //Template method
    {
        LookingForSchool(); //Request school information
        ApplyForEnrol();    //Application for admission
        ApplyForPassport(); //Handle passports, exit cards and notarization for going abroad for private purposes
        ApplyForVisa();     //apply for a visa
        ReadyGoAbroad();    //Physical examination, air ticket booking, packing preparation
        Arriving();         //arrive
    }

    public void ApplyForPassport() {
        System.out.println("three.Handling passports, exit cards and notarization for going abroad for private purposes:");
        System.out.println("  1)Apply to the local public security organ for a private passport and exit card with the admission notice, my residence booklet or ID card.");
        System.out.println("  2)Handle birth notarization, notarization of education, degree and achievement, experience certificate, notarization of kinship and notarization of 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 foreign visa, including personal education, transcripts and proof of work experience; Proof of personal and family income, funds and property; Relationship certificate of family members, etc;");
        System.out.println("  2)To the embassies of countries to study in China(collar)The embassy applies for an entry visa. When applying, you need to fill in the relevant forms, submit the necessary supporting materials and pay the visa. Some countries(For example, the United States, Britain, Canada, etc)When applying for a visa, the applicant will be asked to go to the embassy(collar)Interview at the museum.");
    }

    public void ReadyGoAbroad() {
        System.out.println("five.Physical examination, air ticket booking and packing preparation:");
        System.out.println("  1)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();//Request school information

    public abstract void ApplyForEnrol();   //Application for admission

    public abstract void Arriving();        //arrive
}

//Specific sub category: studying in the United States
class StudyInAmerica extends StudyAbroad {
    @Override
    public void LookingForSchool() {
        System.out.println("one.Request the following information from the school:");
        System.out.println("  1)To have a comprehensive understanding of the political, economic, cultural background, educational system and academic level of the countries intending to study abroad;");
        System.out.println("  2)Fully understand and master the situation of foreign schools, including history, tuition fees, school system, major, teacher allocation, 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 a study abroad agency company authorized to recruit students in China?");
        System.out.println("  5)Master the study visa situation;");
        System.out.println("  6)Does the government allow foreign students to work legally?");
        System.out.println("  8)Can I emigrate after graduation?");
        System.out.println("  9)Is the diploma recognized in China?");
    }

    @Override
    public void ApplyForEnrol() {
        System.out.println("two.Application for admission:");
        System.out.println("  1)Fill in the application form;");
        System.out.println("  2)Send the application form, personal academic certificate, recent academic transcript, recommendation letter, resume, TOEFL or IELTS language test transcript and other materials to the school you are applying for;");
        System.out.println("  3)In order to leave enough time for visa processing, it is suggested that the earlier you apply, the better. It is generally easier to apply one year in advance.");
    }

    @Override
    public void Arriving() {
        System.out.println("six.Arrive at the 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:

one.Request the following information from the school:
  1)To have a comprehensive understanding of the political, economic, cultural background, educational system and academic level of the countries intending to study abroad;
  2)Fully understand and master the situation of foreign schools, including history, tuition fees, school system, major, teacher allocation, teaching facilities, academic status, number of students, etc;
  3)Understand the accommodation, transportation and medical insurance of the school;
  4)Does the school have a study abroad agency company authorized to recruit students in China?
  5)Master the study visa situation;
  6)Does the government allow foreign students to work legally?
  8)Can I emigrate after graduation?
  9)Is the diploma recognized in China?
two.Application for admission:
  1)Fill in the application form;
  2)Send the application form, personal academic certificate, recent academic transcript, recommendation letter, resume, TOEFL or IELTS language test transcript and other materials to the school you are applying for;
  3)In order to leave enough time for visa processing, it is suggested that the earlier you apply, the better. It is generally easier to apply one year in advance.
three.Handling passports, exit cards and notarization for going abroad for private purposes:
  1)Apply to the local public security organ for a private passport and exit card with the admission notice, my residence booklet or ID card.
  2)Handle birth notarization, notarization of education, degree and achievement, experience certificate, notarization of kinship and notarization of economic guarantee.
four.apply for a visa:
  1)Prepare all kinds of materials required for applying for foreign visa, including personal education, transcripts and proof of work experience; Proof of personal and family income, funds and property; Relationship certificate of family members, etc;
  2)To the embassies of countries to study in China(collar)The embassy applies for an entry visa. When applying, you need to fill in the relevant forms, submit the necessary supporting materials and pay the visa. Some countries(For example, the United States, Britain, Canada, etc)When applying for a visa, the applicant will be asked to go to the embassy(collar)Interview at the museum.
five.Physical examination, air ticket booking and packing preparation:
  1)Physical examination, immune examination and vaccination against infectious diseases;
  2)Determine the ticket time, flight and transfer location.
six.Arrive at the 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.

  • The overall steps of the algorithm are very fixed, but when individual parts are changeable, you can use the template method pattern to abstract the easily changeable parts for subclass implementation.
  • When several subclasses have common behavior, they can be extracted and concentrated in a common parent class to avoid code duplication. First, we need to - identify the differences in the existing code and separate the differences into new operations. Finally, replace the different code with a template method that calls these new operations.
  • When it is necessary to control the extension of subclasses, the template method only calls the hook operation at specific points, so it is only allowed to extend at these points.

Mode extension

In the template method pattern, the basic methods include abstract methods, concrete methods and hook methods. The correct use of "hook methods" can enable the subclass to 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 hook methods HookMethod1() and HookMethod2() in the specific subclass. Its structure is shown in Figure 3.

The program code is as follows:

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

//Abstract class with hook method
abstract class HookAbstractClass {
    //Template method
    public void TemplateMethod() {
        abstractMethod1();
        HookMethod1();
        if (HookMethod2()) {
            SpecificMethod();
        }
        abstractMethod2();
    }

    //Specific method
    public void SpecificMethod() {
        System.out.println("Concrete methods in abstract classes are called...");
    }

    //Hook method 1
    public void HookMethod1() {
    }

    //Hook method 2
    public boolean HookMethod2() {
        return true;
    }

    //Abstract method 1
    public abstract void abstractMethod1();

    //Abstract method 2
    public abstract void abstractMethod2();
}

//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 is 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 is 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.