409
阿里云
技术社区[云栖]
Java设计模式:策略模式
下面是一个有关于策略模式的故事。假设Mike在开车的时候,会很频繁的加速,有一天因为超速他被一个警察拦下来了。有可能这个警察会比较友好,没开任何罚单就让Mike把车开走了。(我们把这类型的警察称之为“NicePolice”)。也有可能Mike遇到了一个不太友好的警察,然后这个警察给Mike出具了一张罚单。(我们把这类型的警察称之为“HardPolice”)。
Mike其实并不知道他会遇到什么类型的警察,直到他因为超速而被警察要求停车下来,实际上这就是一种程序当中“运行时”的概念,只有在运行的时候,才知道,到底会遇到什么类型的警察,实际上这就是“策略模式”。

先来定义一个策略的接口:Strategy
1 |
public interface Strategy {
|
2 |
public void processSpeeding( int speed);
|
再来定义两种不同类型的Strategy:
1 |
public class NicePolice implements Strategy {
|
3 |
public void processSpeeding( int speed) {
|
5 |
.println( "This is your first time, be sure don't do it again!" );
|
1 |
public class HardPolice implements Strategy {
|
3 |
public void processSpeeding( int speed) {
|
4 |
System.out.println( "Your speed is " + speed
|
5 |
+ ", and should get a ticket!" );
|
定义一个需要依赖警察来处理超速问题的场景:
01 |
public class Situation {
|
02 |
private Strategy strategy;
|
04 |
public Situation(Strategy strategy){
|
05 |
this .strategy = strategy;
|
08 |
public void handleByPolice( int speed){
|
09 |
this .strategy.processSpeeding(speed);
|
最后,进行测试:
02 |
public static void main(String[] args) {
|
03 |
HardPolice hp = new HardPolice();
|
04 |
NicePolice ep = new NicePolice();
|
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);
|
11 |
// the result based on the kind of police officer.
|
12 |
s1.handleByPolice( 10 );
|
13 |
s2.handleByPolice( 10 );
|
策略模式,实际上就是定义了一些算法,并把他们都封装起来,使得他们之间可以互相替代。实际上对应上面程序,就是定义了两种算法(NicePolice以及HardPolice),由于他们都实现了Strategy这个接口,那么对于依赖于这个接口的实例对象来说,可以动态的对这个依赖进行注入,从而达到运行时确定具体使用哪一种算法的目的。
最后更新:2017-05-23 17:03:22