设计模式|大话设计模式 —— 策略模式

一、模式介绍
策略模式适合封装算法的不同实现(比如上文 大话设计模式 —— 简单工厂模式 中的数学运算)
【设计模式|大话设计模式 —— 策略模式】策略模式能够将实现的细节进一步封装,客户端代码无需知道具体算法实体是什么,就可以完成正确的运算
上文中,客户端(Main.java)实际上是需要了解 Operation 运算父类的,而使用策略模式能够将其屏蔽,进一步解耦
策略模式,将工厂类变成策略类,根据传入参数不同生产不同策略对象(内置),然后提供公开方法
二、使用策略模式实现计算器
上文中的 Operation 接口 、AddOperation、SubOperation、DefaultOperation 继续复用
我们定义一个算法策略

public class ComputeContext {
private Operation opt;
public ComputeContext(String operate) {
switch (operate) {
case "+":
opt = new AddOperation();
break;
case "-":
opt = new SubOperation();
break;
default:
opt = new DefaultOperation();
}
}
public int compute(int num1, int num2) {
return opt.compute(num1, num2);
}
}
测试类(Main 不需要知道 Operation 类的存在,相比简单工厂,进一步解耦了)
public class Main {
public static void main(String[] args) {
ComputeContext ctx = new ComputeContext("+");
System.out.println(ctx.compute(1, 2));
ctx = new ComputeContext("-");
System.out.println(ctx.compute(1, 2));
}
}
设计模式|大话设计模式 —— 策略模式
文章图片

    推荐阅读