Note: for learning purposes only, welcome to comment

In the Strategy Pattern, the behavior of a class or its algorithm can be changed at run time. This type of design pattern is behavioral. In the policy pattern, we create objects that represent various policies and a context object whose behavior changes as the policy object changes. The policy object changes the execution algorithm of the context object.

A, role,

  • Encapsulating role: The entry to the upper-level access policy that holds a reference to the abstract policy role.
  • Abstract policy roles: Provide interfaces or abstract classes that define methods and properties that a policy group must have.
  • Concrete policy roles: Implement abstract policies and define concrete algorithm logic.

Second, the code

public class Context { private Washer strategy; */ Washer (Washer) {this.strategy = strategy; /** * Washer (Washer) {this.strategy = strategy; } public static void main(String[] args) { Context context = new Context(new Often()); context.contextInterface(); Context contextB = new Context(new Speediness()); contextB.contextInterface(); } /** * call policy */ public void contextInterface() {strategy.algorithmLogic(); }} /** ** window Washer {public void algorithmLogic(); } /** ** ** ** ** ** ** ** ** ** ** ** * System.out.println("===>>> > washer "); } /** ** ** ** ** ** ** ** ** ** ** ** ** * System.out.println("===>>> > Washer fast mode "); }}Copy the code

Three, advantages and disadvantages

Advantages:

  1. Algorithms can be switched freely.
  2. Avoid using multiple conditional judgments.
  3. Good scalability.

Disadvantages:

  1. Too many policy classes, resulting in too many classes.
  2. All policy classes need to be exposed.

If a system has more than four policies, you need to consider using mixed mode to solve the problem of policy class inflation.