模式定义
策略模式(Strategy Pattern)定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法独立于使用算法的客户而变化。
模式结构
- Context:环境类
 
- Strategy:抽象策略类
 
- ConcreteStrategy:具体策略类
 

模式案例
不同的鸭子或许会有不同的飞行模式,又或许两种不同的鸭子有相似的飞行模式。对此我们可以使用策略模式来设计不同的飞行模式,即可提高代码的复用,也易于飞行模式的扩展。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
   | // Context-环境类 -> 鸭子 public class Duck { 	FlyBehavior flyBehavior;       	public void performFly() {       	this.flyBehavior.fly();    	}    	public void setFlyBehavior(FlyBehavior flyBehavior) {       	this.flyBehavior = flyBehavior; 	} }
  // Strategy-抽象策略类 -> 飞行行为 public interface FlyBehavior { 	public void fly(); }
  // ConcreteStrategy-具体策略类 // 算法1 public class FlyWithWings implements FlyBehavior { 	 	@Override   	public void fly() {     	System.out.println("I'm flying with wings");   	} }
  // 算法2 public class FlyNoWay implements FlyBehavior {   	   	@Override   	public void fly() {       	System.out.println("I can't fly");   	} }
  // test-测试类 public class DuckTest {   	   	public static void main(String[] args) {       	Duck duck = new Duck();       	duck.setFlyBehavior(new FlyWithWings());       	// "I'm flying with wings"         duck.performFly();       	duck.setFlyBehavior(new FlyNoWay());       	// "I can't fly"         duck.performFly();   	} }
   | 
 
模式分析
优点:
- 策略模式提供了“开闭原则”的完美支持,用户可以在不修改原有系统的基础上选择算法或行为,也可以灵活地增加新的算法或行为。
 
- 策略模式提供了管理相关的算法则的办法。
 
- 策略模式提供了可以利用组合替换继承的办法。
 
- 策略模式可以避免使用多重条件(if..else..)语句。
 
缺点:
- 客户端必须知道所有的策略类,并自行决定使用哪一个策略类。即在设计接口时,必须适当的暴露出全部的接口。
 
- 策略模式将造成产生很多策略类,但相对于未使用设计模式管理算法族来说,比较容易管理。
 
参考资料:
[1] http://design-patterns.readthedocs.io/zh_CN/latest/behavioral_patterns/strategy.html
[2] http://blog.csdn.net/hguisu/article/details/7558249/