What are strategic patterns?

Strategy Pattern: Define a series of algorithms, encapsulate each algorithm, and make them interchangeable. A Policy pattern, also known as a Policy pattern, allows an algorithm to change independently of the customers that use it.

In the process of software development, we often encounter such a situation: in order to achieve a certain function, we have multiple implementation methods, algorithms or strategies. For example, for search algorithms, to provide a variety of search algorithms, you can write these algorithms in a class, in the class to provide multiple methods, each method corresponds to a specific search algorithm; It is also possible to encapsulate these lookup algorithms in a unified method by using if… The else… Or case or other conditional statement to select. If a new search algorithm needs to be added, the source code of the encapsulation algorithm class needs to be modified. Changing the lookup algorithm also requires modifying the client calling code. A large number of search algorithms are encapsulated in this algorithm class, and the code of this class will be complex and difficult to maintain. If we included these policies on the client side, this would be even less desirable, resulting in client programs that were large and difficult to maintain, which would be even worse if there were a large number of algorithms to choose from.

The structure of the organization

Let’s look at the specifics of the strategy pattern

  • Context: Also known as Context, encapsulates a policy twice, in order to avoid direct invocation of the policy by higher-level modules.
  • Abstract Policy class (Strategy): Usually an interface, when there is repeated logic in various implementation classes, the abstract class is used to encapsulate the common part of the code. In this case, the policy pattern looks more like the template method pattern.
  • ConcreteStrategy classes: concrete policy roles are typically filled by a set of classes that encapsulate the algorithm and can be replaced as needed.

For example

First we need to define our abstraction strategy, encapsulating the interface, common code parts here

public interface Strategy {
	public void operater();
}
Copy the code

Then we implement the corresponding policy class according to the specific requirements

public class strateyA implements Strategy {
	@Override
	public void operater{// implements Strategy A}} public class strateyB implements Strategy {@override public voidoperater() {// Execution mode of policy B}}Copy the code

In the environment class to carry out the secondary encapsulation, it can be seen that we can decide which strategy to use by building functions, and we can also change the strategy used by setStrategy method, and implement the method implemented in the corresponding strategy.

public class Context {
	private Strategy strategy;

	public Context(Strategy strategy) {
	    this.strategy = strategy;
	}

	public void setStrategy(Strategy strategy) {
	    this.strategy = strategy;
	}

	public void operater() { this.strategy.operater(); }}Copy the code

Let’s look at the specific invocation of the caller

public class Client { public static void main(String[] args) { Context context; // I want to use the first strategy context = new context (new strateyA()); context.operater(); // The condition has changed and I want to use the second strategy context.setStrategy(new strateyB()); context.operater(); }}Copy the code

Advantages and Disadvantages

advantages

  • The policy pattern provides perfect support for the “open closed principle”, allowing users to choose algorithms or behaviors without modifying the existing system, or to flexibly add new ones.
  • The policy pattern provides a family of management-related algorithms.
  • The policy pattern provides a way to replace inherited relationships.
  • Use policy patterns to avoid multiple conditional transition statements.

disadvantages

  • The client must know all the policy classes and decide which one to use.
  • Policy mode will create many policy classes, increasing the number of engineering classes (this problem can be mitigated to some extent by using the share mode)

applicable

  • If there are many classes in a system that are distinguished only by their behavior, then using the policy pattern dynamically allows an object to choose one behavior among many behaviors.
  • A system needs to dynamically choose one of several algorithms.
  • If an object has many behaviors, those behaviors can be implemented using multiple conditional selection statements without proper patterns.
  • You do not want the client to know complex data structures related to the algorithm. Encapsulate the algorithm and related data structures in a specific policy class to improve algorithm confidentiality and security.

Contrast policy patterns with state patterns

  • The number of environment class states can determine whether to use policy or state patterns.
  • The environment class of the policy pattern chooses a concrete policy class, and the concrete policy class does not need to care about the environment class. However, the environment class of state mode needs to be put into a specific state due to external factors, so that the state switch can be realized through its method. Therefore, there is a bidirectional correlation between the environment class and the state class.
  • In the policy mode, the client needs to know which specific policy is selected. In the state mode, the client does not need to care about the specific state. The state of the environment class is automatically changed according to the user’s operation.
  • If the object of a class in the system has multiple states, the behavior of different states is different, and these states can be converted to use the state mode; The policy pattern is used when there are multiple implementations of a behavior of a class in the system that are interchangeable

conclusion

Strategy mode is mainly to separate algorithm and use, so that the system has a good extensibility

Policy mode is a simple and commonly used mode. We often use it intentionally or unintentionally during development. Generally speaking, policy mode is not used alone, but mixed with template method mode, factory mode and so on.

Article by Summer wind _Me