preface

Using the template method pattern, common methods can be extracted, reused and extended quickly. The policy pattern is also a behavioral pattern, and acts just like the template method pattern. The most common way for people to nest too many handling methods for if-else is to use the policy pattern.

directory

A, definitions,

Define a set of algorithms, encapsulate each algorithm, and make them interchangeable

Two, mode principle analysis

Public void doSomething(); public void doSomething(); } public class ConcreteStrategy1 implements Strategy{public void doSomething(){ System.out.println(" rules for specific policy 1 "); }} public class AdapteStrategy2 implements Strategy{public void doSomething(){system.out.println (" AdapteStrategy2 implements Strategy "); }} public class Context{private Strategy Strategy = null; Public Context(strategy_strategy){this.strategy = _strategy; } public void doAnyThing(){ this.strategy.doSomething(); }}Copy the code

The high-level module invocation is simple and requires knowing which policy to use to build its objects

Public class Client{public static void main(String[] args){// Declare a concrete Strategy = new ConcreteStrategy1(); Context context = new Context(strategy); / / execution context. DoAnyThing (); }}Copy the code

Iii. Usage Scenarios

  • You only want the client to choose the encapsulated algorithm scenario and not care about the implementation details of the algorithm

  • Scenarios where multiple classes differ only slightly in algorithm or behavior

  • The algorithm needs to switch scenes freely

  • Scenarios where algorithm rules need to be masked

  • Separate scenarios where policies are used from scenarios where policies are created

Four advantages,

  • The algorithm can be switched freely

  • Avoid using multiple conditions

  • Good scalability

Five, the disadvantages

  • The number of policy classes increases, and the possibility of reuse is low

  • All policy classes need to be exposed

  • When you modify the code, you need to understand each policy class and make changes to the usage scenarios