<转>java设计模式:策略模式

来源:互联网 发布:windows 2008 编辑:程序博客网 时间:2024/06/02 19:41
下面是一个有关于策略模式的故事。假设Mike在开车的时候,会很频繁的加速,有一天因为超速他被一个警察拦下来了。有可能这个警察会比较友好,没开任何罚单就让Mike把车开走了。(我们把这类型的警察称之为“NicePolice”)。也有可能Mike遇到了一个不太友好的警察,然后这个警察给Mike出具了一张罚单。(我们把这类型的警察称之为“HardPolice”)。

Mike其实并不知道他会遇到什么类型的警察,直到他因为超速而被警察要求停车下来,实际上这就是一种程序当中“运行时”的概念,只有在运行的时候,才知道,到底会遇到什么类型的警察,实际上这就是“策略模式”。

strategy-pattern-class-diagram


先来定义一个策略的接口:Strategy

public interface Strategy {public void processSpeeding(int speed);}

再来定义两种不同类型的Strategy:

public class NicePolice implements Strategy {@Overridepublic void processSpeeding(int speed) {System.out.println("This is your first time, be sure don't do it again!");}}
public class HardPolice implements Strategy {        @Overridepublic void processSpeeding(int speed) {System.out.println("Your speed is " + speed+ ", and should get a ticket!");}}

定义一个需要依赖警察来处理超速问题的场景:

public class Situation {   private Strategy strategy;      public Situation(Strategy strategy){   this.strategy = strategy;   }      public void handleByPolice(int speed){   this.strategy.processSpeeding(speed);   }}

最后,进行测试:

public class Main {public static void main(String[] args) {HardPolice hp = new HardPolice();NicePolice ep = new NicePolice();// In situation 1, a hard officer is met// In situation 2, a nice officer is metSituation s1 = new Situation(hp);Situation s2 = new Situation(ep);// the result based on the kind of police officer.s1.handleByPolice(10);s2.handleByPolice(10);}}

策略模式,实际上就是定义了一些算法,并把他们都封装起来,使得他们之间可以互相替代。实际上对应上面程序,就是定义了两种算法(NicePolice以及HardPolice),由于他们都实现了Strategy这个接口,那么对于依赖于这个接口的实例对象来说,可以动态的对这个依赖进行注入,从而达到运行时确定具体使用哪一种算法的目的。


0 0