一、创建Strategy抽象类,定义所有支持的算法的公共接口:
public abstract class Strategy {
public abstract void AlgorithmInterface();
}
二、创建一系列ConcreteStrategy类,继承与Strategy:
ConcreteStrategyA:
public class ConcreteStrategyA extends Strategy {
@Override
public void AlgorithmInterface() {
System.out.println("实现 Algorithm A!");
}
}
ConcreteStrategyB:
public class ConcreteStrategyB extends Strategy {
@Override
public void AlgorithmInterface() {
System.out.println("实现 Algorithm B!");
}
}
ConcreteStrategyC:
public class ConcreteStrategyC extends Strategy {
@Override
public void AlgorithmInterface() {
System.out.println("实现 Algorithm C!");
}
}
三、创建Context,用一个ConcreteStrategy来配置、维护一个队Strategy对象的引用:
public class Context {
Strategy strategy;
//初始化时传入具体的策略对象。
public Context(Strategy strategy){
this.strategy = strategy;
}
//上下文接口
//根据具体的策略对象,调用其算法方法
public void ContextInterface(){
strategy.AlgorithmInterface();
}
}
四、StrategyMain:
public class StrategyMain {
public static void main(String[] args) {
Context context;
context = new Context(new ConcreteStrategyA());
context.ContextInterface();
context = new Context(new ConcreteStrategyB());
context.ContextInterface();
context = new Context(new ConcreteStrategyC());
context.ContextInterface();
}
}
五、小结:
策略模式是一种定义一系列算法的模式,从整体看来这些算法的目的都是一致的,只是实现不同。策略模式可以以相同的方式调用所有的算法,减少了算法类与使用算法的类之间的耦合。