"Zen design pattern" of the Template Method Pattern

First, define the template method pattern

Defines a framework of the algorithm in operation, the two delay steps to subclasses. Subclasses that may not change the structure of certain steps of an algorithm of the algorithm to redefine.


Abstract-Class called abstract template, its methods are divided into two categories:

1. Basic Method

The basic method also called the basic operation is implemented by a subclass, and is called the template method.

2. Template Method

There may be one or several, typically a specific method, i.e. a framework to achieve a basic scheduling methods, in fixed logic.

Note:
(1) In order to prevent malicious actions, coupled with the general template methods final keyword is not allowed to be overwritten (rewritten);

The basic method (2) abstract template design is protected as much as possible types, in line with the Law of Demeter, property or method does not need to try not to expose the protected type. Implementation class if not necessary, try not to expand access to parent class;

Second, the application template method pattern

Advantages The method of pattern templates

  • Package invariant portion, a variable extension portion;
  • Extracting common code, easy to maintain;
  • Behavior is controlled by the parent class, subclass implementation;

2. The drawback template method pattern

According to our design custom, abstract class for declaring the most abstract, most general things properties and methods to achieve the completion of specific things like properties and methods. But Template Method pattern has reversed, abstract class defines part of the abstract method, implemented by a subclass, the result of a subclass affecting the implementation of the results of the parent class, which is a subclass of a parent class had an impact on this complex project, It will bring the code more difficult to read, but also make the novice produce discomfort.

3. The template method pattern of usage scenarios

  • A plurality of sub-class has public methods, and the logic is substantially the same;
  • Important, complex algorithms, the core algorithm can be designed as a template method, functional details around by each sub-class implementation;
  • When reconstituted, the template pattern is a method often used the same code pattern to extract parent class, then constrain behavior hook function;

Third, the best practice

The code examples: https://github.com/developers-youcong/DesignPatternPractice/tree/master/Template

Guess you like

Origin www.cnblogs.com/youcong/p/11838332.html