下面是一个有关于策略模式的故事。假设Mike在开车的时候,会很频繁的加速,有一天因为超速他被一个警察拦下来了。有可能这个警察会比较友好,没开任何罚单就让Mike把车开走了。(我们把这类型的警察称之为“NicePolice”)。也有可能Mike遇到了一个不太友好的警察,然后这个警察给Mike出具了一张罚单。(我们把这类型的警察称之为“HardPolice”)。 Mike其实并不知道他会遇到什么类型的警察,直到他因为超速而被警察要求停车下来,实际上这就是一种程序当中“运行时”的概念,只有在运行的时候,才知道,到底会遇到什么类型的警察,实际上这就是“策略模式”。
先来定义一个策略的接口:Strategy
1 public interface Strategy { 2 public void processSpeeding(int speed); 3}再来定义两种不同类型的Strategy:
1 public class NicePolice implements Strategy { 2 @Override 3 public void processSpeeding(int speed) { 4 System.out 5 .println("This is your first time, be sure don't do it again!"); 6 } 7} 1 public class HardPolice implements Strategy { 2 @Override 3 public void processSpeeding(int speed) { 4 System.out.println("Your speed is " + speed 5 + ", and should get a ticket!"); 6 } 7}定义一个需要依赖警察来处理超速问题的场景:
01 public class Situation { 02 private Strategy strategy; 03 04 public Situation(Strategy strategy){ 05 this.strategy = strategy; 06 } 07 08 public void handleByPolice(int speed){ 09 this.strategy.processSpeeding(speed); 10 } 11}最后,进行测试:
01 public class Main { 02 public static void main(String[] args) { 03 HardPolice hp = new HardPolice(); 04 NicePolice ep = new NicePolice(); 05 06 // In situation 1, a hard officer is met 07 // In situation 2, a nice officer is met 08 Situation s1 = new Situation(hp); 09 Situation s2 = new Situation(ep); 10 11 // the result based on the kind of police officer. 12 s1.handleByPolice(10); 13 s2.handleByPolice(10); 14 } 15}策略模式,实际上就是定义了一些算法,并把他们都封装起来,使得他们之间可以互相替代。实际上对应上面程序,就是定义了两种算法(NicePolice以及HardPolice),由于他们都实现了Strategy这个接口,那么对于依赖于这个接口的实例对象来说,可以动态的对这个依赖进行注入,从而达到运行时确定具体使用哪一种算法的目的。
转载自 并发编程网 - ifeve.com 相关资源:敏捷开发V1.0.pptx