logo头像
Snippet 博客主题

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

本文于 452 天之前发表,文中内容可能已经过时。

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

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

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

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

普通策略类

  • 策略模式中的重要角色:context
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();
        // 这样就达到了"屏蔽实现细节,面向抽象编程"
    }
}