Design Patterns in Program Development - Strategy Patterns

What is Strategy Pattern

The strategy pattern defines only a series of algorithms, encapsulates each algorithm, and makes them interchangeable. The strategy pattern lets the algorithm change independently of the clients using the algorithm.

Design Principles of the Strategy Pattern

The design principle of the strategy pattern is to extract the part of a class that changes frequently or may change in the future as an interface, and then contains an instance of the object in the class, so that the instance of the class can be called at will at runtime to implement this The class of the interface.

Three Objects in the Strategy Pattern

  • Environment object: This class implements a reference to the interface or abstract class defined in the abstract strategy.
  • Abstract strategy class: It can have interface or abstract class to implement.
  • Specific strategy object: It encapsulates algorithms that implement different functions.

Advantages and disadvantages of the strategy pattern

advantage

  • Algorithms can be switched freely. By implementing abstract strategies and encapsulating them through roles, it is guaranteed to provide "freely switchable" strategies to the outside world.
  • Avoid using multiple conditional judgments. If there are multiple strategies, then each strategy only needs to implement its own method
  • Good scalability, new strategies can be added arbitrarily in the existing system (need to comply with the OCP principle)

shortcoming

  • The number of policy classes increases, each policy is a class, the possibility of reuse is small, and the number of classes will increase
  • All strategies must be exposed to the outside world, and the upper-level module must know which strategies are available in order to know which corresponding strategy to use (which can be corrected through factory mode, proxy mode, and flyweight mode)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324661686&siteId=291194637
Recommended