Template mode for design mode (template method)

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

For example, when going to a bank to handle business, there are generally 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 is different for different people, it may be deposit, withdrawal or transfer, etc.Can be deferred to subclasses.

There are many examples in life, such as getting up, eating, doing things, sleeping and so on, where the content of "doing things" may vary from day to day. We define these examples of prescribed processes or formats as templates that allow users to update them according to their needs, such as resume templates, paper templates, template files in Word, and so on.

The template approach pattern described below will address similar issues above.

Definition and characteristics of patterns

Definition

Defines the algorithm skeleton in an operation and delays some steps of the algorithm to a subclass so that the subclass can redefine certain steps of the algorithm without changing the structure of the algorithm. It is a class behavior pattern.

Advantage

  1. It encapsulates the invariant part and extends the variable part. It encapsulates the algorithm that is considered the invariant part into the parent class, and implements the variable part algorithm by inheriting from the subclass so that the subclass can continue to expand.
  2. It extracts common parts of code from the parent class to facilitate code reuse.
  3. Some methods are implemented by subclasses, so subclasses can be extended to add appropriate functionality, which conforms to the open-close principle.

shortcoming

  1. Each different implementation requires a subclass to be defined, which increases the number of classes, makes the system larger, makes the design more abstract, and indirectly increases the complexity of the system implementation.
  2. Abstract methods in a parent class are implemented by subclasses, and the results of subclass execution affect the results of the parent class, resulting in a reverse control structure that makes code reading more difficult.
  3. Due to the shortcomings of the inheritance relationship itself, if the parent class adds a new abstract method, all subclasses will be changed again. Structure and implementation of the schema

Structure and implementation of patterns

Template method mode requires attention to collaboration between abstract classes and specific subclasses. It uses polymorphism technology for virtual functions and reverse control technology for "Let me call you instead of calling me". Now we will describe their basic structure.

1.The structure of the pattern

The template method pattern contains the following main roles.

1) Abstract Class/Template (Abstract Class)

An abstract template class responsible for outlining and skeleton an algorithm. It consists of a template method and several basic methods. These methods are defined as follows.

(1) Template method: Defines the framework of the algorithm and calls the basic methods it contains in some order.

(2) Basic method: It is a step in the whole algorithm and contains the following types.
Abstract method: declared in an abstract class and implemented by a specific subclass.
Specific method: Implemented in an abstract class, inherited or overridden in a specific subclass.
Hook method: Implemented in abstract classes, including logical methods for judgment and empty methods that require subclass overrides.

2) Specific subclasses/implementations (Concrete Class)

Specific implementation classes that implement the abstract methods and hook methods defined in the abstract class are a component step of top-level logic.

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

2.Implementation of patterns

The code for the template method pattern 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 methods
    public void SpecificMethod() {
        System.out.println("Specific methods in abstract classes are called...");
    }
    //Abstract Method 1
    public abstract void abstractMethod1();
    //Abstract Method 2
    public abstract void abstractMethod2();
}
//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 results of the program are as follows:

Specific 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] Use the template method mode to implement the procedure design procedures for studying abroad.

Analysis: The procedures for studying abroad generally go through the following processes: obtaining school information, applying for admission, handling for passports, exit cards and certificates for going abroad privately, applying for visas, checking up, booking tickets, preparing to pack, arriving at the target school, etc. Some of them are the same for each school, but some of them are different for different schools, so they are more suitable to use the template method mode.To achieve.

In this example, we first define an abstract class, StudyAbroad, which contains a template method, TemplateMethod().This method contains various basic methods in the process of going abroad to study. Some of them can be implemented in abstract classes because they are the same in different countries. However, some methods are different in different countries and must be handled in their specific subclasses (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 Class: Study Abroad
abstract class StudyAbroad {
    public void TemplateMethod() //Template Method
    {
        LookingForSchool(); //Request school information
        ApplyForEnrol();    //Application for Admission
        ApplyForPassport(); //Handle exit passports, exit cards and notarization for private reasons
        ApplyForVisa();     //Apply for a visa
        ReadyGoAbroad();    //Check-up, booking tickets, preparing packages
        Arriving();         //Arrive
    }
    public void ApplyForPassport() {
        System.out.println("three.Processing passports, exit cards and notarization for private purposes:");
        System.out.println("  1)Apply to the public security organ of the place where the residence is located for handling the passport and exit card for private reasons by holding the acceptance notice, my residence book or identity card.");
        System.out.println("  2)Handle the notarization of birth certificates, academic qualifications, academic degrees and achievements, experience certificates, relatives and economic guarantees.");
    }
    public void ApplyForVisa() {
        System.out.println("four.Apply for a visa:");
        System.out.println("  1)Prepare all kinds of materials needed to apply for foreign visas, including certificates of personal qualifications, report cards, work experience; certificates of personal and family income, funds and property; certificates of family members'relationship, etc.");
        System.out.println("  2)Ambassador to China to a Country Ready to Study(collar)The library applies for an entry visa. When applying, it must fill in the relevant forms as required, submit the necessary supporting materials and pay the visa. Some countries have(Such as the United States, the United Kingdom, Canada and so on)When applying for a visa, the applicant is required to go to the envoy(collar)The library has an interview.");
    }
    public void ReadyGoAbroad() {
        System.out.println("five.Check-up, booking tickets, preparation for packing:");
        System.out.println("  1)Conduct physical examinations, immune tests 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 Subcategory: Study in the United States
class StudyInAmerica extends StudyAbroad {
    @Override
    public void LookingForSchool() {
        System.out.println("one.The following information was obtained 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 country with the intention to study abroad;");
        System.out.println("  2)Fully understand and master the situation of foreign schools, including history, tuition, education system, specialty, faculty, teaching facilities, academic status, number of students, etc.");
        System.out.println("  3)Learn about the accommodation, transportation and medical insurance of the school;");
        System.out.println("  4)Does the school have an authorized agent for enrollment in China?");
        System.out.println("  5)Master the status of study abroad visas;");
        System.out.println("  6)Does the government allow international students to work legally?");
        System.out.println("  8)Can I migrate after graduation?");
        System.out.println("  9)Is the diploma recognized by our country?");
    }
    @Override
    public void ApplyForEnrol() {
        System.out.println("two.Application for Admission:");
        System.out.println("  1)Fill in the registration form;");
        System.out.println("  2)Send the application form, personal qualification certificate, recent academic record, recommendation letter, resume, TOEFL or IELTS language test results to the school you are applying for.");
        System.out.println("  3)In order to allow enough time for visa processing, it is recommended 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.Arrive at target school:");
        System.out.println("  1)Arrange accommodation;");
        System.out.println("  2)Learn about the campus and its surroundings.");
    }
}

The results of the program are as follows:

one.The following information was obtained from the school:
  1)To have a comprehensive understanding of the political, economic, cultural background, educational system and academic level of the country with the intention to study abroad;
  2)Fully understand and master the situation of foreign schools, including history, tuition, education system, specialty, faculty, teaching facilities, academic status, number of students, etc.
  3)Learn about the accommodation, transportation and medical insurance of the school;
  4)Does the school have an authorized agent for enrollment in China?
  5)Master the status of study abroad visas;
  6)Does the government allow international students to work legally?
  8)Can I migrate after graduation?
  9)Is the diploma recognized by our country?
two.Application for Admission:
  1)Fill in the registration form;
  2)Send the application form, personal qualification certificate, recent academic record, recommendation letter, resume, TOEFL or IELTS language test results to the school you are applying for.
  3)In order to allow enough time for visa processing, it is recommended that the earlier the application is, the better. Generally, it is easier to apply one year in advance.
three.Processing passports, exit cards and notarization for private purposes:
  1)Apply to the public security organ of the place where the residence is located for handling the passport and exit card for private reasons by holding the acceptance notice, my residence book or identity card.
  2)Handle the notarization of birth certificates, academic qualifications, academic degrees and achievements, experience certificates, relatives and economic guarantees.
four.Apply for a visa:
  1)Prepare all kinds of materials needed to apply for foreign visas, including certificates of personal qualifications, report cards, work experience; certificates of personal and family income, funds and property; certificates of family members'relationship, etc.
  2)Ambassador to China to a Country Ready to Study(collar)The library applies for an entry visa. When applying, it must fill in the relevant forms as required, submit the necessary supporting materials and pay the visa. Some countries have(Such as the United States, the United Kingdom, Canada and so on)When applying for a visa, the applicant is required to go to the envoy(collar)The library has an interview.
five.Check-up, booking tickets, preparation for packing:
  1)Conduct physical examinations, immune tests and vaccination against infectious diseases;
  2)Determine the ticket time, flight and transfer location.
six.Arrive at target school:
  1)Arrange accommodation;
  2)Learn about the campus and its surroundings.

Scenarios for applying patterns

Template method patterns are generally applicable in the following scenarios.

  • The overall steps of the algorithm are fixed, but when individual parts of the algorithm are volatile, the template method pattern can be used to abstract the volatile parts for subclasses to implement.
  • When multiple subclasses have common behavior, they can be extracted and aggregated into a common parent class to avoid code duplication. First, identify differences in existing code and separate them into new operations. Finally, replace these different codes with a template method that calls these new operations.
  • When you need to control the extension of subclasses, template methods invoke hook operations only at specific points, allowing expansion only at those points.

Tags: Design Pattern

Posted on Tue, 14 Sep 2021 17:43:18 -0400 by mrherman