define

Defining a set of algorithms, encapsulating them one by one, and making them interchangeable, this pattern allows the algorithm to change independently of the customers that use it.

nature

Separate algorithm, select implementation.

His role

  • Strategy

    Responsible for determining the interfaces necessary to implement policies that constrain a specific set of policy algorithms.

  • ConcreteStrategy

    Implement specific policies (strategies, directions, algorithms, etc.).

  • Context

    Responsible for using the policy role, saved the policy role instance, and used it to implement the function.

Code sample

/** * policy, Used to constrain a set of specific strategy algorithms */ public interface CalculateStrategy {/** * Calculate the number of kilometers by distance * @param km * @return */ int calculatePrice(int km); } /** * public implements CalculateStrategy{@override public int calculatePrice(int km) */ return km * 1; */ return km * 1; } /** * public class SubwayStrategy implements CalculateStrategy{@override public int calculatePrice(int) Km) {/** * return km * 2; }} /** * context, role using policy */ public class TranficCalculator {CalculateStrategy mCalculateStrategy; public static void main(String[] args){ TranficCalculator tranficCalculator = new TranficCalculator(); tranficCalculator.setmCalculateStrategy(new BusStrategy()); System.out.println(" bus price calculation "); System.out.println(tranficCalculator.calculatePrice(3)); tranficCalculator.setmCalculateStrategy(new SubwayStrategy()); System.out.println(" subway price calculation "); System.out.println(tranficCalculator.calculatePrice(3)); } public void setmCalculateStrategy(CalculateStrategy mCalculateStrategy) { this.mCalculateStrategy = mCalculateStrategy; } public int calculatePrice(int km){ return mCalculateStrategy.calculatePrice(km); }}Copy the code

The results

Calculate the bus price 3 calculate the subway price 6Copy the code

advantages

  • Define a set of algorithms that are interchangeable with each other.
  • Avoid multiple conditional statements.
  • Better scalability, extending new algorithms is very easy, just need to calculate the policy abstract class or interface.

disadvantages

  • You must understand the differences of each strategy when using it.
  • Because the number of conditional statements is reduced, the number of objects is increased because it can be viewed as a split of conditional statements.

When to use

  • Multiple ways of dealing with the same type of problem are only different when specific behaviors are different.
  • When you need to securely encapsulate multiple operations of the same type.
  • When there are multiple subclasses of the same abstract class and you need to use if-else or switch-case to select the specific subclass.