您的位置:首页 > 其它

Design Patterns学习笔记:Strategy策略模式

2007-08-08 17:51 507 查看
导读:
这段时间在项目中接触到了Strategy策略模式,所以就学习了一下,做一个总结。
Strategy策略模式是一种对象行为模式。主要是应对:在软件构建过程中,某些对象使用的算法可能多种多样,经常发生变化。如果在对象内部实现这些算法,将会使对象变得异常复杂,甚至会造成性能上的负担。
GoF《设计模式》中说道:定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换。该模式使得算法可独立于它们的客户变化。
Strategy模式的结构图如下:



从图中我们不难看出:Strategy模式实际上就是将算法一一封装起来,如图上的ConcreteStrategyA、ConcreteStrategyB、ConcreteStrategyC,但是它们都继承于一个接口,这样在Context调用时就可以以多态的方式来实现对于不用算法的调用。
Strategy模式的实现如下:
我们现在来看一个场景:我在下班在回家的路上,可以有这几种选择,走路、骑车、坐车。首先,我们需要把算法抽象出来:
publicinterfaceIStrategy
{
voidOnTheWay();
}
接下来,我们需要实现走路、骑车和坐车几种方式。
publicclassWalkStrategy: IStrategy
{
publicvoidOnTheWay()
{
Console.WriteLine("Walk on the road");
}
}
publicclassRideBickStragtegy: IStrategy
{
publicvoidOnTheWay()
{
Console.WriteLine("Ride the bicycle on the road");
}
}
publicclassCarStragtegy: IStrategy
{
publicvoidOnTheWay()
{
Console.WriteLine("Drive the car on the road");
}
}
最后再用客户端代码调用封装的算法接口,实现一个走路回家的场景:
classProgram
{
staticvoidMain(string[] args)
{
Console.WriteLine("Arrive to home");
IStrategystrategy = newWalkStrategy();
strategy.OnTheWay();
Console.Read();
}
}
运行结果如下;
Arrive to home
Walk on the road
如果我们需要实现其他的方法,只需要在Context改变一下IStrategy所示例化的对象就可以。
Strategy模式的要点:
1、Strategy及其子类为组件提供了一系列可重用的算法,从而可以使得类型在运行时方便地根据需要在各个算法之间进行切换。所谓封装算法,支持算法的变化。
2、Strategy模式提供了用条件判断语句以外的另一中选择,消除条件判断语句,就是在解耦合。含有许多条件判断语句的代码通常都需要Strategy模式。
3、Strategy模式已算法为中心,可以和Factory Method联合使用,在工厂中使用配制文件对变化的点进行动态的配置。这样就使变化放到了运行时。
4、与Template Method相比,Strategy模式的中心跟集中在方法的封装上
本文转自
http://www.cnblogs.com/kid-li/archive/2006/12/15/592818.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: