Template method pattern
What is the template method pattern?
Define the skeleton of the algorithm in an operation, and delay some steps to the subclass. The template method allows subclasses to redefine some specific steps of an algorithm without changing the structure of the algorithm.
Structure elucidation
There are two basic types of methods in abstract class:
- Basic method: a method implemented by a subclass and called in a template method.
- Template method: a method that combines basic operation methods to form a total algorithm or a total behavior; an abstract class can have any number of template methods, but not limited to one. Each template method can call any number of concrete methods.
Concrete class is the basic method to realize the abstract definition of parent class.
/** * Abstract classes defining template methods */ public abstract class AbstractClass { /** * Primitive operation 1, the so-called primitive operation is an abstract operation, which must be implemented by subclasses */ public abstract void doPrimitiveOperation1(); /** * Primitive operation 2 */ public abstract void doPrimitiveOperation2(); /** * Template method, defining algorithm skeleton */ public final void templateMethod() { doPrimitiveOperation1(); doPrimitiveOperation2(); } } /** * Specific implementation class to realize template operation */ public class ConcreteClass extends AbstractClass { public void doPrimitiveOperation1() { //Specific implementation } public void doPrimitiveOperation2() { //Specific implementation } }
Application example
Using 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 (), which contains various basic methods in the process of going through the formalities for studying abroad. Some of the methods can be implemented in the abstract class because all countries are the same, but some of the methods are different from each other It must be implemented in its specific subclass (such as StudyInAmerica). If you add another country, just add a subclass.
The program code is as follows:
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 passport and exit card for private use by holding 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 situation for 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."); } }
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 some parts are changeable, template method mode can be used to abstract the changeable parts for subclass implementation.
- 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.
- 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.