1、概念
定义了一个算法簇,对每个算法进行封装,使得算法之间可以相互代替。
2、 UML类图
3、java代码实现
抽象策略角色:策略类,通常是一个接口或抽象类
public abstract class Strategy {
public abstract void algorithmInterface();
}
具体策略角色A、B、C:包装了相关的算法和行为
public class ConcreteStrategyA extends Strategy {
@Override
public void algorithmInterface() {
System.out.println("ConcreteStrategyA");
}
}
public class ConcreteStrategyB extends Strategy {
@Override
public void algorithmInterface() {
System.out.println("ConcreteStrategyB");
}
}
public class ConcreteStrategyC extends Strategy {
@Override
public void algorithmInterface() {
System.out.println("ConcreteStrategyC");
}
}
环境角色:维护一个策略类的引用,供客户端调用
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void contextInterface() {
if (this.strategy != null) {
strategy.algorithmInterface();
}
}
}
测试
@Test
public void testStrategy() {
Context contextA = new Context(new ConcreteStrategyA());
contextA.contextInterface();
Context contextB = new Context(new ConcreteStrategyB());
contextB.contextInterface();
Context contextC = new Context(new ConcreteStrategyC());
contextC.contextInterface();
}
测试结果
ConcreteStrategyA
ConcreteStrategyB
ConcreteStrategyC
以上代码实现了一个"策略模式"的案例,不过以上代码要求客户端知道具体使用哪个策略,之间存在耦合;可通过"简单工厂模式"修改环境角色的代码来实现解耦,具体代码如下
public class Context {
private Strategy strategy;
public Context(String type) {
switch (type) {
case "A" :
this.strategy = new ConcreteStrategyA();
break;
case "B" :
this.strategy = new ConcreteStrategyB();
break;
case "C" :
this.strategy = new ConcreteStrategyC();
break;
}
}
public void contextInterface() {
if (this.strategy != null) {
strategy.algorithmInterface();
}
}
}
测试
@Test
public void testStrategy() {
Context contextA = new Context("A");
contextA.contextInterface();
Context contextB = new Context("B");
contextB.contextInterface();
Context contextC = new Context("C");
contextC.contextInterface();
}
测试结果
ConcreteStrategyA
ConcreteStrategyB
ConcreteStrategyC
4、总结
优点:提供管理相关算法簇的方法;提供可以替换继承关系的方法;避免使用多重条件转移语句。
缺点:客户端必须知道所有的策略类,并自行决定使用哪一个策略类;策略模式造成很多的策略类,每个具体策略类都会产生一个新类。