模式结构:
Context:环境类
Strategy:抽象策略类
ConcreteStrategy:具体策略类
UML图:
例子代码:
环境类:
public class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void algorithm(){
strategy.algorithm();
}
}
public interface Strategy {
void algorithm();
}
具体策略类A:
public class ConcreteAlgorithmA implements Strategy {
@Override
public void algorithm() {
System.out.println("使用策略A");
}
}
具体策略类B:
public class ConcreteAlgorithmB implements Strategy {
@Override
public void algorithm() {
System.out.println("使用策略B");
}
}
客户类:
public class Client {
public static void main(String[] args) {
//准备决策环境
Context context = new Context();
//实例化使用的策略
Strategy strategy1 = new ConcreteAlgorithmA();
Strategy strategy2 = new ConcreteAlgorithmB();
//环境设置策略
context.setStrategy(strategy1);
context.algorithm();
//根据不同策略输出不同结果
context.setStrategy(strategy2);
context.algorithm();
}
}
结果打印: