策略模式的目的是定义一系列算法,把它们封装起来,并且使它们可以相互替换.
本模式使得算法可以独立于它的客户而变话.
本模式使得算法可以独立于它的客户而变话.
![](http://dl.iteye.com/upload/attachment/595599/9b15bac7-fa09-33ce-835d-8cd885660fea.png)
- /**
- * 抽象策略(Strategy)角色
- * @author Salmon
- *
- */
- public interface Strategy {
- public void algorithmInterface();
- }
- /**
- * 具体策略(ConcreteStrategy)角色
- * @author Salmon
- *
- */
- public class ConcreteStrategyA implements Strategy {
- public void algorithmInterface() {
- System.out.println("Called ConcreteStrategyA.algorithmInterface()");
- }
- }
- /**
- * 具体策略(ConcreteStrategy)角色
- * @author Salmon
- *
- */
- public class ConcreteStrategyB implements Strategy {
- public void algorithmInterface() {
- System.out.println("Called ConcreteStrategyB.algorithmInterface()");
- }
- }
- /**
- * 具体策略(ConcreteStrategy)角色
- * @author Salmon
- *
- */
- public class ConcreteStrategyC implements Strategy {
- public void algorithmInterface() {
- System.out.println("Called ConcreteStrategyC.algorithmInterface()");
- }
- }
- /**
- * 环境(Context)角色
- * @author Salmon
- *
- */
- public class Context {
- Strategy strategy;
- public Context(Strategy strategy) {
- this.strategy = strategy;
- }
- public void contextInterface() {
- strategy.algorithmInterface();
- }
- }
- /**
- * 客户端代码
- * @author Salmon
- *
- */
- public class Client {
- public static void Main(String[] args) {
- Context c = new Context(new ConcreteStrategyA());
- c.contextInterface();
- Context d = new Context(new ConcreteStrategyB());
- d.contextInterface();
- Context e = new Context(new ConcreteStrategyC());
- e.contextInterface();
- }
- }
应用场合:
1、多个类的分别只是在于行为的不同。
2、你需要对行为的算法做很多的变动。
3、客户不知道算法要使用的数据。