场景:当不同条件调用不同的算法或者策略时。
优点:1.可以减少大量的if else,减少耦合度。
2.方便扩展和维护
缺点:1.类的数量变多,机构变复杂了。
2.向外暴露了策略
类图:
代码:
策略接口
1. public interface Strategy { 2. public void method(); 3. }
策略实现
1. public class StrategyA implements Strategy { 2. @Override 3. public void methodA() { 4. System.out.println("方法A"); 5. } 6. }
1. public class StrategyB implements Strategy { 2. @Override 3. public void methodB() { 4. System.out.println("方法B"); 5. } 6. }
1. public class StrategyC implements Strategy { 2. @Override 3. public void methodC() { 4. System.out.println("方法C"); 5. } 6. }
上下文角色
1. public class Context { 2. //抽象策略 3. private Strategy strategy = null; 4. //构造函数设置具体策略 5. public Context(Strategy strategy) { 6. this.strategy = strategy; 7. } 8. public void setContext(Strategy strategy) { 9. this.strategy = strategy; 10. } 11. //封装后的策略方法 12. public void doMethod() { 13. this.strategy.method(); 14. } 15. }
调用(如果为了美化 可以将这个类设计为工厂 这样可以保持对入口的统一管理)
1. public class Client { 2. public static void main(String[] args) { 3. //声明上下文对象 4. Context context = new Context(); 5. context.setContext(new StrategyA()); 6. //执行封装后的方法 7. context.method(); 8. context.setContext(new StrategyB()); 9. //执行封装后的方法 10. context.method(); 11. } 12. }