Design Mode: Template Method template method mode

Source: Internet
Author: User

Template Method template method mode

 1. Definition

Template Method mode defines an operation inAlgorithmAnd delay some steps to the subclass. The template method allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.

 2. Description

What is "template "? The template is a specific method in this mode. This method sets a set of steps for implementing an algorithm. Any steps can be abstract and implemented by sub-classes. This ensures that the algorithm structure remains unchanged and is partially implemented by sub-classes.
The template method mode implements the unchanged part of an algorithm at one time (for example, the algorithm implementation step), and leaves the variable behavior to the subclass for implementation. It helps us to remove duplicates in similar methods contained in sub-classes of the same class hierarchy.Code.
The unchanged behavior in the template method mode consists of the following:

 I. Call methods and call sequence;

Ii. Rewrite abstract methods that must be overwritten by subclass;

Iii. Hook methods that subclass may override;

 

3. UML

In the UML diagram, the templatemethod in the parent class is an abstract method, which calls four methods in a certain order-primitiveopertion1, primitiveopertion2, concreteopertion, and hook. primitiveopertion1 and operator are abstract methods, child classes are required to be implemented based on specific conditions, but the overall framework of the algorithm is controlled by the templatemethod method in the parent class.

4. Use
For the client, how does one use a class structure that implements the template method mode?
The PHP code is as follows:

 
  $ Subclass2 = NewSubclass2 ();
$ Subclass2->Templatemethod ();

 

5. Conclusion

The template method mode is a relatively simple design mode, which is also common and should be mastered.

 

References: reconstruction and Model

Head first design model

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.