设计模式-策略模式与工厂模式结合

策略模式有个弱点,就是使用方需要知道所有的策略算法,这不符合迪米特原则.

可以借助工厂模式,创建出策略类,使得使用方与实现方解耦,让其满足迪米特原则

这么说,有点抽象,下面举例子

普通策略类

public class Context {

    private  Strategy strategy;


    public  Context(Strategy strategy){
        this.strategy = strategy;
    }

    public void exect(){
        strategy.excute();
    }
}
public class Client {

    public static void main(String[] args) {
        Context context = new Context(new AddStrategy()); // 需要知道具体策略类
        context.exect();
    }
}

加入工厂模式

public class StrategyFactory {

    public Strategy getStrategy(String opt) {
        if (opt.equals("+")) {
            return new AddStrategy();
        }
        if (opt.equals("*")) {
            return new MultStrategy();
        }
        return null;
    }
}
public class Client {

    public static void main(String[] args) {
        StrategyFactory strategyFactory = new StrategyFactory();
        strategyFactory.getStrategy("*").excute();
		// 这样就达到了"屏蔽实现细节,面向抽象编程"
    }
}