设计模式之策略模式
?? 策略模式(strategy)属于对象的行为模式,将一组算法封装在一个具有共同接口的独立类中,这组算法
?? 可以在不影响客户端的情况下互换。类图如下:
?
Context:
?
package com.cmj.pattern.strategy;public class Context{ private Strategy strategy; public void contextInterface() { strategy.algorithm(); }}
?
?
strategy:
?
package com.cmj.pattern.strategy;abstract public class Strategy{ public abstract void algorithm ();}
?
?StrategyImpl1
?
package com.cmj.pattern.strategy;public class StrategyImpl1 extends Strategy{ public void algorithm () { //write you algorithm code here }}
?
?
? 从类图中我们可以看到,通过一个算法接口封装算法,把使用算法的环境和具体的算法分隔开来,算法的变化,不会影响环境。
?
设计思想的体现:??
?策略模式是“开闭原则”很好的体现,对扩展开发也就是对增加新的算法开放,对修改关闭也就是不会影响环境,不会影响其它?的算法;其实这些根本上是通过多态来实现的。
?? 同时也是“里氏代换原则”很好的体现,一个程序如果使用的是一个基类的话,那么也一定适用于其子类,而此程序根本没有觉察到子类和父类的区别。
???