I. Strategic mode

public class StrategyContext { Strategy strategy; public StrategyContext(Strategy strategy) { this.strategy = strategy; } /** * */ public int context(int a, int b) { return strategy.operator(a,b); }}Copy the code

The core of the strategy pattern is the StrategyContext class, which holds the Strategy object and performs operations in the context.

The test class

public class StrategyContextTest { public static void main(String[] args) { Strategy strategy; strategy = new OperationAdd(); StrategyContext strategyContext = new StrategyContext(strategy); The strategy. The operator (5, 2); }}Copy the code

Technical notes

1. How to use the policy pattern to solve the if else or Switch problem

Policy mode + reflection

The policy pattern still seems to use if else to decide which class to call, so after the policy pattern was introduced, reflection was added to the context class.

public class StrategyContext {
    Strategy strategy;

    public StrategyContext(String type) throws Exception {
        Class clazz = Class.forName(type);
        this.strategy = (Strategy) clazz.newInstance();
    }

    /**
     * 
     */
    public int context(int a, int b) {
        return strategy.operator(a,b);
    }
Copy the code

Of course, the type here can be solved by an enumeration. There’s no need to feel the cost is too high, but the readability of the code is improved.

The source code:

[gitee.com/hankzhousan…

gitee.com

] (link.zhihu.com/?target=htt…).