Strategy(策略模式):是对对象的策略的封装,可以选择并使用需要的策略

优点:可以动态的选择并使用策略
缺点:客户必须知道所有的策略,并自行选择使用那一种策略
代码模型:有一个抽象策略接口,有若干个继承了这个抽象策略接口的具体策略,有一个包含了抽象策略接口变量的对象。那么在客户调用该对象时可以使用某个具体的策略来向上转型成抽象策略,这也是一种多态的表现。这样就实现了策略的动态选择,不过这里讨论的是方法的动态实现而已。

 

Java代码 设计模式_策略模式 _策略 设计模式_策略模式 _设计_02
  1. /**
  2. * 抽象策略
  3. * @author wly
  4. *
  5. */
  6. public interface AbstractStrategy {
  7.  
  8. void someMethod();
  9. }
Java代码 设计模式_策略模式 _策略 设计模式_策略模式 _设计_02
  1. /**
  2. * 一个具体的策略类
  3. * @author wly
  4. *
  5. */
  6. public class A_Strategy implements AbstractStrategy {
  7.  
  8. @Override
  9. public void someMethod() {
  10. // 具体的策略方法一
  11. System.out.println("This is A_Strategy.someMethod");
  12. }
  13. }
Java代码 设计模式_策略模式 _策略 设计模式_策略模式 _设计_02
  1. public class B_Strategy implements AbstractStrategy {
  2.  
  3. @Override
  4. public void someMethod() {
  5. // 这又是一个具体的策略方法
  6. System.out.println("This is B_Startegy.someMethod");
  7. }
  8.  
  9. }
Java代码 设计模式_策略模式 _策略 设计模式_策略模式 _设计_02
  1. /**
  2. * 环境对象,包含了抽象策略的引用变量
  3. * @author wly
  4. *
  5. */
  6. public class SomeObject {
  7.  
  8. private AbstractStrategy abstractStrategy;
  9.  
  10. public SomeObject(AbstractStrategy abstractStrategy) {
  11. this.abstractStrategy = abstractStrategy;
  12. }
  13.  
  14. public void someMethod() {
  15. abstractStrategy.someMethod();
  16. }
  17. }
Java代码 设计模式_策略模式 _策略 设计模式_策略模式 _设计_02
  1. /**
  2. * 客户类
  3. * @author wly
  4. *
  5. */
  6. public class Test {
  7.  
  8. public static void main(String[] args){
  9.  
  10. SomeObject _so = new SomeObject(new A_Strategy());
  11. _so.someMethod();
  12.  
  13. _so = new SomeObject(new B_Strategy());
  14. _so.someMethod();
  15.  
  16. }
  17. }
  18.  
  19. //输出:
  20. //This is A_Strategy.someMethod
  21. //This is B_Startegy.someMethod