用途
策略模式是一种
行为型模式。
结构
图-策略模式结构图
Strategy : 定义所有算法的公共接口(AlgorithmInterface)。Context 使用这个接口去调用 ConcreteStrategy 定义的具体算法。
abstract
class Strategy {
public abstract void AlgorithmInterface();
}
public abstract void AlgorithmInterface();
}
ConcreteStrategy : 实现 Strategy 中的算法接口(AlgorithmInterface)。
class ConcreteStrategyA
extends Strategy {
@Override
public void AlgorithmInterface() {
System.out.println("算法A");
}
}
class ConcreteStrategyB extends Strategy {
@Override
public void AlgorithmInterface() {
System.out.println("算法B");
}
}
class ConcreteStrategyC extends Strategy {
@Override
public void AlgorithmInterface() {
System.out.println("算法C");
}
}
@Override
public void AlgorithmInterface() {
System.out.println("算法A");
}
}
class ConcreteStrategyB extends Strategy {
@Override
public void AlgorithmInterface() {
System.out.println("算法B");
}
}
class ConcreteStrategyC extends Strategy {
@Override
public void AlgorithmInterface() {
System.out.println("算法C");
}
}
Context : 用一个 ConcreteStrategy 来配置。维护一个对 Strategy 对象的引用。
class Context {
Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void ContextInterface() {
strategy.AlgorithmInterface();
}
}
Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void ContextInterface() {
strategy.AlgorithmInterface();
}
}
测试代码
public
class StrategyPattern {
public static void main(String[] args) {
Context context1 = new Context( new ConcreteStrategyA());
context1.ContextInterface();
Context context2 = new Context( new ConcreteStrategyB());
context2.ContextInterface();
Context context3 = new Context( new ConcreteStrategyC());
context3.ContextInterface();
}
}
public static void main(String[] args) {
Context context1 = new Context( new ConcreteStrategyA());
context1.ContextInterface();
Context context2 = new Context( new ConcreteStrategyB());
context2.ContextInterface();
Context context3 = new Context( new ConcreteStrategyC());
context3.ContextInterface();
}
}
运行结果
算法A
算法B
算法C
算法B
算法C