I. Overview
The strategy design pattern is to extract the realization of the function and form a unified interface.
Provides a unified interface parameter method.
2. Code implementation
Here is an example of paying taxes.
[1] Policy interface
public interface CalculateTax { // A unified interface, the input parameters of the method are salary and bonus double calculate( double salary , double bouns); }
[2] Implementation of the strategy
// A simple calculation method public class SimpleStrategy implements CalculateTax{ private static final double salary_ratio = 0.1d ; private static final double bouns_ratio = 0.2d ; //现在的计算方式 public double calculate(double salary, double bouns) { return salary * salary_ratio + bouns * bouns_ratio; } }
[3] call place
// tax calculator public class TaxCalculator { // Calculate tax // The parameters of the method require a strategy to pass in public static double countTax( double salary , double bouns ,CalculateTax strategy) { return strategy.calculate(salary, bouns); } }
[4] Test
public class TestClass { public static void main(String[] args) { System.out.println(TaxCalculator.countTax(1000, 1000, new SimpleStrategy())); } }
3. Description
(1) There are two cores of design patterns
[1] Policy interface
[2] Interface (abstract type) is used at the call site
(2) Benefits: When our strategy changes, we can program in a consistent way.
(3) When we use a framework like spring, we can use the configuration method to deal with it.
That is to say, when we need to modify, we only need to create a new class, and then modify the configuration to complete.