设计模式之策略模式
程序员文章站
2022-06-13 12:52:57
...
策略模式是指有一定行动内容的相对稳定的策略名称。一定的策略模式,既可应用于战略决策,也可应用于战术决策;既可实施于大系统的全局性行动,也可实施于大系统的局部性行动。
组成:
抽象策略角色(strategy): 策略类,通常由一个接口或者抽象类实现。
具体策略角色(ConcreteStrategy):包装了相关的算法和行为。
环境角色(Context):持有一个策略类的引用,最终给客户端调用。
UML图如下
具体列子:
抽象策略角色(strategy)
public interface Operation {
public int execute(int num1,int num2);
}
具体策略角色(ConcreteStrategy)
public class OperationAdd implements Operation {
@Override
public int execute(int num1, int num2) {
return num1 + num2;
}
}
public class OperationSub implements Operation {
@Override
public int execute(int num1, int num2) {
return num1 - num2;
}
}
环境角色(Context)
public class Calculator {
private Operation operation;
public void setOperation(Operation operation) {
this.operation = operation;
}
public int execute(int num1,int num2) {
return operation.execute(num1, num2);
}
}
测试
public class Test {
public static void main(String[] args) {
Calculator cal = new Calculator();
Operation operation = new OperationAdd();
// Operation operation = new OperationSub();
cal.setOperation(operation);
int num = cal.execute(5, 3);
System.out.println("num = " + num);
}
}
如需要添加新的计算规则,只要再添加一个具体策略角色(ConcreteStrategy)即可
public class OperationMul implements Operation {
@Override
public int execute(int num1, int num2) {
return num1 * num2;
}
}
测试
public class Test {
public static void main(String[] args) {
Calculator cal = new Calculator();
// Operation operation = new OperationAdd();
// Operation operation = new OperationSub();
Operation operation = new OperationMul();
cal.setOperation(operation);
int num = cal.execute(5, 3);
System.out.println("num = " + num);
}
}
下一篇: I/O多路复用 - select