一、策略模式简介(Brief Introduction)
定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独 立于使用它的客户而变化二、解决的问题(What To Solve)
策略模式的重心不是如何来实现算法,而是如何组织、调用这些算法,从而让程序结构更灵活,具有更好的维护性喝扩展性三、命令模式分析(Analysis)
Strategy:策略接口,用来约束一系列具体的策略算法。Context使用这个接口来调用具体的策略实现定义的算法
ConcreteStrategy:具体的策略实现,也就是具体的算法实现
Context:上下文,负责和具体的策略类交互,通常上下文会持有一个真正的策略实现,上下文还可让具体的策略类来获取上下文的数据,甚至让具体的策略类来回调上下文的方法
四、实例代码
1、策略接口及其实现
public interface Strategy {
public void algorithmInterface();
}
public class ConcreteStrategyA implements Strategy {
public void algorithmInterface() {
System.out.println("====算法A实现====");
}
}
public class ConcreteStrategyB implements Strategy {
public void algorithmInterface() {
System.out.println("====算法B实现====");
}
}
public class ConcreteStrategyC implements Strategy {
public void algorithmInterface() {
System.out.println("====算法C实现====");
}
}
2、上下文Context
public class Context {
private Strategy strategy = null;
public Context(Strategy strategy){
this.strategy = strategy;
}
public void contextInterface(){
this.strategy.algorithmInterface();
}
}
3、客户端调用
public class Client {
public static void main(String[] args) {
Strategy strategyA = new ConcreteStrategyA();
Strategy strategyB = new ConcreteStrategyB();
Strategy strategyC = new ConcreteStrategyC();
Context contextA = new Context(strategyA);
Context contextB = new Context(strategyB);
Context contextC = new Context(strategyC);
contextA.contextInterface();
System.out.println();
contextB.contextInterface();
System.out.println();
contextC.contextInterface();
}
}
运行结果: