设计模式之策略模式
2013-12-22 21:28
260 查看
1 概述
策略模式(Strategy Patern),是把针对同一件事情的不同的算法分别封装起来,并且相互之间可以替换。这种模式的使用需要以下三种角色:(1)环境角色:应用不同的策略来达到完成某件事情的目的;
(2)抽象策略角色:通常由接口或者抽象类实现,所有的具体角色都继承此抽象;
(3)具体策略角色:具体的算法实现;
2 示例
相对来说,例子还是挺多的,比如淘宝搜索的时候,是按照卖出量排序还是价格排序还是好评度排序等等。前面的几种模式都是拿手机做例子,那还是继续手机做例子吧。
现在的智能手机基本上都是大屏幕,看着花里胡哨的很爽。流行的手机操作系统都支持换屏幕主题的功能。不同的Theme有着不同的背景图、图标、字体。用户还能自定义特殊癖好的主题。
首先来个接口,所有的手机主题都必须实现此接口:
package org.scott.strategy; /** * @author Scott * @date 2013年12月22日 * @description */ public interface Theme { public void backGround(); public void fontStyle(); public void smsRing(); }
接口中定义了三个方法,分别是背景图片、字体类型、通知铃声。有了抽象策略角色,下面就实现两个具体的主题策略:
package org.scott.strategy; /** * @author Scott * @date 2013年12月22日 * @description */ public class ClassficTheme implements Theme { @Override public void backGround() { System.out.println("Back ground image is: 水墨中国.jpeg."); } @Override public void fontStyle() { System.out.println("Font style is: 正楷."); } @Override public void smsRing() { System.out.println("The sms ring is: 春江花月夜"); } }
再来个现代风格的主题:
package org.scott.strategy; /** * @author Scott * @date 2013年12月22日 * @description */ public class ModernTheme implements Theme { @Override public void backGround() { System.out.println("Back ground image is: 奇幻星空.jpeg."); } @Override public void fontStyle() { System.out.println("Font style is: 静蕾体."); } @Override public void smsRing() { System.out.println("The sms ring is: Nohthing In The World."); } }
有了抽象策略和具体策略,还差个Context角色:
package org.scott.strategy; /** * @author Scott * @date 2013年12月22日 * @description */ public class Context { private Theme theme; public void setTheme(Theme theme) { this.theme = theme; } public void getTheme(){ theme.backGround(); theme.fontStyle(); theme.smsRing(); } }
我们来个手机设定个Theme吧,看看我们的客户端代码:
package org.scott.strategy; /** * @author Scott * @date 2013年12月22日 * @description */ public class StrategyClient { public static void main(String[] args) { Context theme = new Context(); theme.setTheme(new ClassficTheme()); theme.getTheme(); } }
执行结果呢?
Back ground image is: 水墨中国.jpeg. Font style is: 正楷. The sms ring is: 春江花月夜
3 小结
策略模式一个很大的特点就是各个策略算法的平等性。对于一系列具体的策略算法,大家的地位是完全一样的,正因为这个平等性,才能实现算法之间可以相互替换。所有的策略算法在实现上也是相互独立的,相互之间没有依赖。并且,在运行期间,策略模式在每一个时刻只能使用一个具体的策略实现对象,虽然可以动态地在不同的策略实现中切换,但是同时只能使用一个。就像我们的例子,只能使用一个主题,这个可以理解,你只有一个手机,一个屏幕~
最后上个经典的类图吧(源自网络):
相关文章推荐
- 我的写作
- Thrift解读(一)——TNonblockingServer 连接管理
- Mybatis常见错误
- 手势
- 从基础开始,从一个SQLHelper开始
- Add Subtitle (srt) to Video by using Ffmpeg
- 机房收费系统—封装函数
- error LNK2001: unresolved external symbol __imp__PathFileExistsA@4
- 设计模式之策略模式
- 关于c/c++中sizeof的资源
- error LNK2001: unresolved external symbol __imp__PathFileExistsA@4
- ZOJ-2345
- MyBabitsXML中遍历以及插入语句返回ID
- ajax学习笔记
- 数制转换
- POJ1042 钓鱼
- hdu 4292 Food 最大流
- Clojure 学习入门(5)—— 关键字
- hdu 4292 Food 最大流
- Python并发编程的几篇文章