2策略模式

策略 + 工厂

package strategy;
public abstract class Strategy {
    public abstract double getResult();
}
package strategy;

public class StrategyA extends Strategy{
    @Override
    public double getResult() {
        System.out.println("策略A实现了");
        return 1.0;
    }
}
package strategy;

public class StrategyB extends Strategy{
    @Override
    public double getResult() {
        System.out.println("策略B实现了");
        return 2.0;
    }
}
package strategy;

public class StrategyC extends Strategy{
    @Override
    public double getResult() {
        System.out.println("策略C实现了");
        return 3.0;
    }
}
package strategy;

/**
 * 工厂
 */
public class Context {
    private Strategy strategy;
    public Context(String type){
        switch (type){
            case "A":
                strategy = new StrategyA();
                break;
            case "B":
                strategy = new StrategyB();
                break;
            case "C":
                strategy = new StrategyC();
                break;
        }
    }
    public double getResult(){
        return strategy.getResult();
    }
}
package strategy;

/**
 * 客户端
 */
public class TestStrategy {
    public static void main(String[] args) {
        Context context = new Context("A");
        double result = context.getResult();
        System.out.println("result = " + result);
    }
}

商场收银软件:


图片来自《大话设计模式》

优点

  1. 修改Context不会影响客户端和strategy,修改strategy也不会影响到客户端和其他strategy
  2. 可以单独对某一strategy进行单元测试
  3. 修改哪个模块,只需要编译对应的模块
posted @ 2025-02-03 21:46  yx1024  阅读(29)  评论(0)    收藏  举报