您的位置:首页 > 编程语言 > Java开发

讲故事学设计模式-策略(Strategy)模式

2014-04-08 22:02 507 查看
策略模式(Strategy Pattern)又称政策模式(Policy Pattern)。

这是一个关于策略模式的小故事:想象Mike开车时偶尔会超速,但他并不经常这样。他有时会被警察逮住。假如这个警察非常好(nice),不开罚单或者只进行口头警告就放他走。(我们称这类警察为“好心叔叔”)。假如他被一个很严厉的警察抓住,并给他开出罚单(我们称这为警察为“坏心叔叔”)。直到他被抓出才知道遇到了哪种警察——这就是运行期,这就是策略模式的核心。

1、类图



2、源码

定义一个接口Strategy,它只有一个方法processSpeeding();
public interface Strategy {
//defind a method for police to process speeding case.
public void processSpeeding(int speed);
}

于是,我们可以得到这两类警察
public class NicePolice implements Strategy{
@Override
public void processSpeeding(int speed) {
System.out.println("This is your first time, be sure don't do it again!");
}
}

public class HardPolice implements Strategy{
@Override
public void processSpeeding(int speed) {
System.out.println("Your speed is "+ speed+ ", and should get a ticket!");
}
}

定义警察处理超速的situation类
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 met
Situation s1 = new Situation(hp);
Situation s2 = new Situation(ep);

//the result based on the kind of police officer.
s1.handleByPolice(10);
s2.handleByPolice(10);
}
}

输出:

Your speed is 10, and should get a ticket!
This is your first time, be sure don't do it again!

你可以和状态模式(State Pattern)对比,两者很相似。最大的不同之处在于:状态模式通过改变对象的状态来改变对象的行为(功能),而策略模式是在不同情况下使用不同的算法。

3、在JDK中的应用

1). Java.util.Collections#sort(List list, Comparator < ? super T > c)

2). java.util.Arrays#sort(T[], Comparator < ? super T > c)

sort方法在不同的情况下调用不同的Comparator。

原文链接:http://www.programcreek.com/2011/01/a-java-example-of-strategy-design-pattern/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息