Strategy(策略模式):是对对象的策略的封装,可以选择并使用需要的策略
优点:可以动态的选择并使用策略
缺点:客户必须知道所有的策略,并自行选择使用那一种策略
代码模型:有一个抽象策略接口,有若干个继承了这个抽象策略接口的具体策略,有一个包含了抽象策略接口变量的对象。那么在客户调用该对象时可以使用某个具体的策略来向上转型成抽象策略,这也是一种多态的表现。这样就实现了策略的动态选择,不过这里讨论的是方法的动态实现而已。
- /**
- * 抽象策略
- * @author wly
- *
- */
- public interface AbstractStrategy {
- void someMethod();
- }
/** * 抽象策略 * @author wly * */ public interface AbstractStrategy { void someMethod(); }
- /**
- * 一个具体的策略类
- * @author wly
- *
- */
- public class A_Strategy implements AbstractStrategy {
- @Override
- public void someMethod() {
- // 具体的策略方法一
- System.out.println("This is A_Strategy.someMethod");
- }
- }
/** * 一个具体的策略类 * @author wly * */ public class A_Strategy implements AbstractStrategy { @Override public void someMethod() { // 具体的策略方法一 System.out.println("This is A_Strategy.someMethod"); } }
- public class B_Strategy implements AbstractStrategy {
- @Override
- public void someMethod() {
- // 这又是一个具体的策略方法
- System.out.println("This is B_Startegy.someMethod");
- }
- }
public class B_Strategy implements AbstractStrategy { @Override public void someMethod() { // 这又是一个具体的策略方法 System.out.println("This is B_Startegy.someMethod"); } }
- /**
- * 环境对象,包含了抽象策略的引用变量
- * @author wly
- *
- */
- public class SomeObject {
- private AbstractStrategy abstractStrategy;
- public SomeObject(AbstractStrategy abstractStrategy) {
- this.abstractStrategy = abstractStrategy;
- }
- public void someMethod() {
- abstractStrategy.someMethod();
- }
- }
/** * 环境对象,包含了抽象策略的引用变量 * @author wly * */ public class SomeObject { private AbstractStrategy abstractStrategy; public SomeObject(AbstractStrategy abstractStrategy) { this.abstractStrategy = abstractStrategy; } public void someMethod() { abstractStrategy.someMethod(); } }
- /**
- * 客户类
- * @author wly
- *
- */
- public class Test {
- public static void main(String[] args){
- SomeObject _so = new SomeObject(new A_Strategy());
- _so.someMethod();
- _so = new SomeObject(new B_Strategy());
- _so.someMethod();
- }
- }
- //输出:
- //This is A_Strategy.someMethod
- //This is B_Startegy.someMethod