讲故事学设计模式-策略(Strategy)模式
2014-04-08 22:02
507 查看
策略模式(Strategy Pattern)又称政策模式(Policy Pattern)。
这是一个关于策略模式的小故事:想象Mike开车时偶尔会超速,但他并不经常这样。他有时会被警察逮住。假如这个警察非常好(nice),不开罚单或者只进行口头警告就放他走。(我们称这类警察为“好心叔叔”)。假如他被一个很严厉的警察抓住,并给他开出罚单(我们称这为警察为“坏心叔叔”)。直到他被抓出才知道遇到了哪种警察——这就是运行期,这就是策略模式的核心。
于是,我们可以得到这两类警察
定义警察处理超速的situation类
最后,测试的主函数如下:
输出:
你可以和状态模式(State Pattern)对比,两者很相似。最大的不同之处在于:状态模式通过改变对象的状态来改变对象的行为(功能),而策略模式是在不同情况下使用不同的算法。
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/
这是一个关于策略模式的小故事:想象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/
相关文章推荐
- 设计模式 ( 十八 ) 策略模式Strategy(对象行为型)
- 【设计模式】—— 策略模式Strategy
- Java设计模式透析之 —— 策略(Strategy)
- [设计模式]策略模式,strategy
- java设计模式之 strategy策略模式
- Java开发中的23种设计模式详解----策略模式(strategy)
- 设计模式(二十一)----- 策略模式(Strategy)----(JAVA版)
- 设计模式之策略模式-strategy
- C++设计模式之策略模式(Strategy)
- 设计模式 - 策略模式(Strategy)
- Java 设计模式--策略(Strategy)
- php设计模式 Strategy(策略模式)
- Java设计模式透析之 —— 策略(Strategy)
- 设计模式之策略模式(Strategy)&&Comparable、Comparator接口
- Java设计模式(18)策略模式(Strategy模式)
- 设计模式(一)The Strategy Pattern 策略模式
- 设计模式之Strategy(策略)
- Java 设计模式-策略模式(Strategy)Android讲解
- 设计模式之策略模式strategyPattern
- iOS 设计模式之策略模式( Strategy)