Design mode-template mode

Source: Internet
Author: User

Definition: The template method pattern is the behavior pattern of the class.

Prepare an abstract class, implement some of the logic in the form of concrete methods and concrete constructors, and then declare some abstract methods to force subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways, thus having different implementations of the remaining logic. This is the intent of the template method pattern.

Role:


  

Abstract template roles have the following responsibilities:

One or more abstract operations are defined to allow subclasses to implement. These abstractions are called basic operations, and they are the constituent steps of a top-level logic.

Defines and implements a template method. This template method is generally a concrete method, it gives a top-level logic of the skeleton, and the logical composition of the steps in the corresponding abstract operation, deferred to the sub-class implementation. It is also possible for top-level logic to invoke some concrete methods.

The concrete template role also has the following responsibilities:

Implement one or more of the abstract methods defined by the parent class, which are the constituent steps of a top-level logic.

Each abstract template role can have any number of specific template roles corresponding to it, and each specific template role can give a different implementation of these abstract methods (that is, the constituent steps of top-level logic), so that the implementation of the top-level logic varies.

Advantages:

1. Encapsulate the invariant part and extend the variable part. The algorithm that considers the invariant part is encapsulated in the parent class implementation, while the variable part can continue to be extended through inheritance.

2. Extract the public part code for easy maintenance. The detour we just walked through in our example is the best proof that if we don't extract the parent class, let this messy code take place, think about what the consequences look like? Maintenance personnel to fix a flaw, need to look for similar code everywhere!

3. Behavior control is implemented by subclasses. The basic method is implemented by subclasses, so subclasses can extend the function in a way that conforms to the opening and shutting principle.

Disadvantages:

According to our design habits, abstract class is responsible for declaring the most abstract, most general things properties and methods, implementation of the class to complete specific things properties and methods, but the template method mode is reversed, the abstract class defines a partial abstract method, sub-class implementation, the result of child class execution affects the result of the parent class, that is, the subclass has an impact In complex projects, it can be difficult to read code, and it can make the novice feel uncomfortable.
Usage scenarios for Template method patterns

Usage scenarios for Template method patterns

1. Multiple subclasses have a public method, and the logic is essentially the same.

2. Important and complex algorithms, the core algorithm can be designed as a template method, the surrounding details of the relevant functions are implemented by each sub-class.

3. When refactoring, the template method pattern is a frequently used pattern that extracts the same code into the parent class and then constrains its behavior through the hook function.

Instance:

The basic methods of the abstract template role class, Abstractmethod (), Hookmethod () are the constituent steps of the top-level logic, represented by the Templatemethod () method.
  

 Public Abstract  class abstracttemplate {    /** * Template method * /     Public void Templatemethod(){//Call basic methodAbstractmethod ();        Hookmethod ();    Concretemethod (); }/** * Declaration of the Basic method (implemented by subclasses) */    protected Abstract void Abstractmethod();/** * Basic Method (empty method) */    protected void Hookmethod(){}/** * Basic method (already implemented) */    Private Final void Concretemethod(){//Business-related code}}
A concrete template role class that implements the basic method declared by the parent class,

The Abstractmethod () method represents the remaining logic that enforces the subclass implementation, and the Hookmethod () method is an optional implementation of the logic that is not required to be implemented.

publicclass ConcreteTemplate extends AbstractTemplate{    //基本方法的实现    @Override    publicvoidabstractMethod() {        //业务相关的代码    }    //重写父类的方法    @Override    publicvoidhookMethod() {        //业务相关的代码    }}
Method Template method in Template method pattern

A template method is defined in an abstract class that combines basic operational methods to form a total algorithm or a method of total behavior.

An abstract class can have any number of template methods, not limited to one. Each template method can invoke any number of specific methods.

The basic methods can be divided into three kinds: abstract method, Concrete method (concrete method) and hook methods.

Abstract method: An abstract method is declared by an abstract class and implemented by a specific subclass. In the Java language, abstract methods are indicated by the Abstraction keyword.

Concrete method: A concrete method is declared and implemented by an abstract class, and the subclass is not implemented or replaced.

Hook method: A hook method is declared and implemented by an abstract class, and subclasses are extended. Usually the implementation given by an abstract class is an empty implementation, as the default implementation of the method.

In the example above, Abstracttemplate is an abstract class with three methods. where Abstractmethod () is an abstract method, which is declared by an abstract class as an abstract method and implemented by a subclass; Hookmethod () is a hook method that is declared by an abstract class and provides a default implementation, and is displaced by subclasses. Concretemethod () is a concrete method that is declared and implemented by an abstract class.

Default Hook method

A hook method is often given by an abstract class to an empty implementation as the default implementation of this method. This empty hook method is called "Do nothing Hook". Obviously, this default hook method has already been seen in the default adaptation mode, and a default adaptation mode is that a class provides a default null implementation for an interface, so that the subclass of the default adaptation class does not have to give the implementation of all the methods as the implementation of the interface, because usually a concrete class does not need all the methods.

Naming rules

  
The name of the hook method should begin with do, which is a standard practice for Java developers who are familiar with design patterns. In the above example, the Hook method Hookmethod () should start with do, and in the HttpServlet class, this naming convention, such as Doget (), DoPost (), is also followed.

My QR code is as follows, welcome to exchange discussion

You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:

Reference:
Head First design mode
Http://www.cnblogs.com/java-my-life/archive/2012/05/14/2495235.html
Https://github.com/nivance/DPModel/tree/master/src/dp/com/company/template_method

Design mode-template mode

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.