Template method, strategy method

Template method

Definition: Define an operation 算法骨架, and delay some steps of the algorithm to the subclass , so that the subclass can redefine some specific steps of the algorithm without changing the structure of the algorithm . It is a kind of behavioral pattern.

Pros and cons

advantage:

  1. It encapsulates the immutable part and extends the variable part . It encapsulates the algorithm that is considered to be the immutable part into the parent class for implementation, while the variable part of the algorithm is inherited and implemented by the subclass, so that the subclass can continue to expand;
  2. It extracts part of the common code in the parent class to facilitate code reuse ;
  3. Some methods are implemented by subclasses, so subclasses can add corresponding functions through extensions , which conform to the principle of opening and closing.

Disadvantages:

  1. For each different implementation, you need to define a subclass, which will increase the number of classes , the system will be larger, and the design will be abstract;
  2. The abstract method in the parent class is implemented by the child class, and the result of the execution of the child class will affect the result of the parent class, which leads to a reverse control structure, which increases the difficulty of code reading .

Applicable scene

  1. The overall steps of the algorithm are very fixed , but when individual parts of them are changeable, the template method pattern can be applied at this time to abstract the changeable parts for subclasses to implement.
  2. When multiple subclasses have common behaviors , they can be extracted and concentrated into a common parent class to avoid code duplication.
  3. When you need to control the extension of a subclass , the template method is only called at specific points 钩子操作, so that extensions are only allowed at these points.

main character

  • Abstract Class (AbstractClass): Responsible for giving the outline and skeleton of an algorithm, including the following methods:
  1. Template method (写公有方法,已经定义好的公有模板,无需再子类中重写): defines the skeleton of the algorithm, and calls its basic methods in a certain order:
  2. Basic method: It is a step in the whole algorithm , including the following types:
    (1). Abstract method: Declared in the abstract class and implemented by concrete subclasses.
    (2). Concrete method: It has been implemented in the abstract class, and it can be inherited or rewritten in the concrete subclass.
    (3). Hook method: It has been implemented in the abstract class, including two kinds of logic methods for judgment and empty methods that need to be rewritten by subclasses .
  • Concrete subclass (ConcreteClass): implements the abstract methods and hook methods defined in the abstract class, which are a constituent step of a top-level logic.

Structure chart

Insert picture description here
Example: The procedures for studying abroad generally go through the following procedures: requesting school information, submitting an application for admission, applying for a private passport, departure card and notarization, applying for a visa, experiencing, booking air tickets, preparing for packing, arriving at the target school, etc.; some of these services are for each individual The schools are the same, but some businesses differ from school to school. Use the template method pattern to achieve. The structure diagram is as follows:
Insert picture description here

Strategy mode

Definition: This model defines a series of algorithms and encapsulates each algorithm so that they can be replaced with each other, and the change of the algorithm will not affect the customers who use the algorithm.

Pros and cons

advantage:

  1. Multiple conditional statement is not easy to maintain, and use the strategy pattern can avoid the use of multiple conditional statements ;
  2. The strategy mode provides a series of algorithm clusters that can be reused. Proper use of inheritance can transfer the common code of the algorithm cluster to the parent class, thereby avoiding duplication of code ;
  3. The strategy mode can provide different realizations of the same behavior , and customers can choose different strategies according to different time or space requirements;
  4. The strategy mode provides perfect support for the "opening and closing principle" , which can flexibly add new algorithms without modifying the source code;
  5. The strategy mode puts the use of the algorithm in the environment class, and the realization of the algorithm is moved to the specific strategy class, realizing the separation of the two .

Disadvantages:
1. The client must understand the difference between all strategy algorithms in order to select the appropriate algorithm class in time.
2. The strategy pattern creates a lot of strategy classes .

Application scenarios of strategy mode

  1. When a system needs to dynamically select one of several algorithms, each algorithm can be encapsulated into a strategy class.
  2. A class defines multiple behaviors , and these behaviors appear in the form of multiple conditional statements in the operation of this class. Each conditional branch can be moved into their respective strategy classes to replace these conditional statements.
  3. When the algorithms in the system are completely independent of each other , and customers are required to hide the implementation details of specific algorithms.
  4. When the system requires that the customer who uses the algorithm should not know the data of its operation , the strategy mode can be used to hide the data structure related to the algorithm.
  5. Multiple classes only differ in their performance behaviors . You can use the strategy mode to dynamically select specific behaviors to be executed at runtime.

The main role of the strategy mode:

  1. Abstract strategy (Strategy) class: defines a public interface, and various algorithms implement this interface in different ways. Environmental actors use this interface to call different algorithms, generally implemented by interfaces or abstract classes.
  2. Concrete Strategy (ConcreteStrategy) class: implements the interface defined by the abstract strategy and provides specific algorithm implementation.
  3. Environment (Context) class: holds a reference to a strategy class, which is finally called by the client.

Structure chart

Insert picture description here
Example: There are many ways to make hairy crab dishes. In this example, two methods of steamed hairy crabs and braised hairy crabs are used as examples to introduce the application of the strategy model. The structure diagram is as follows:
Insert picture description here

Expansion of the pattern

In a system that uses the strategy mode, when there are many strategies, the client manages all the strategy algorithms will become very complicated. If the simple factory mode is used in the environment class to manage these strategy classes, the work complexity of the client will be greatly reduced. , The structure diagram is as follows:

Insert picture description here

Note: The contents of the article picking in the "software design patterns (Java version)", Author: Cheng fine column

The interface can be replaced by an abstract class, but not vice versa;

Guess you like

Origin blog.csdn.net/weixin_44048668/article/details/109305218