concept

An interface is provided to encapsulate a series of algorithms (policies) with different implementation classes of the interface, which can be replaced with each other to meet different business requirements. Dynamic replacement of algorithms and policies can be realized on the client side by injecting different implementation objects. Advantages are easy to expand, complete packaging; The disadvantage is that the number of subclasses increases as the policy increases.

Usage scenarios

  • There are many ways to deal with the same type of problem
  • When there are multiple subclasses of the same abstract class and many if-else selections are required

implementation

interface Strategy {
    void fun();
}

public class Strategy1 implements Strategy {
    public void fun() {/ /do something
    }
}

public class Strategy2 implements Strategy {
    public void fun() {/ /do something
    }
}

public class Test{
    Strategy mStrategy;
    public static void main(String[] args){
       Test t = new Test();
       t.setStrategy(new Strategy1());
       t.mStrategy.fun();
    }
    public void setStrategy(Strategy s){ mStrategy = s; }}Copy the code