(4)结构
Strategy的结构如下图所示
下面简要介绍一下以上类图中各个类的作用:
(1) Context类为上下文类,负责维护和更新算法所要处理的环境和数据。譬如对于图象压
缩来说,Context负责数据的提取、压缩参数的获得以及压缩以后善后工作等等; (2) Strategy代表抽象的算法,譬如对于图象压缩来说,它代表的就是图象压缩算法,至于具体那种压缩?JEPG压缩还是GIF压缩,Strategy类不关心,它只为具体的图象压缩算法提供统一的接口;
(3)ConcreteStrategyA、ConcreteStrategyB、ConcreteStrategyC则代表特别具体的算法。 Context类维护Strategy的一个引用(或者指针)。一旦Context所维护的上下文有变(譬如输入数据有变化),它就将这个职责转发给它的Strategy对象。Context的客户制定应该使用哪一种Strategy(算法)的方式是直接将它想要的具体的
Strategy (ConcreteStrategyA、ConcreteStrategyB、ConcreteStrategyC )装入Composition中。
(5)实用性
当存在一下情况时,适合使用Strategy模式
(a) 许多相关的类仅仅是行为上的差异。“策略”提供了一种用多个行为中的一个行为类配置一个类的方法;
(b) 需要使用一个算法的不同的变体。例如,您可能会定义一些反映不同空间/时间权衡的算法。当这些变体实现为一个算法的类层次时,可以使用策略模式;
(c) 算法使用客户不应该知道的具体的实现步骤,可以使用策略模式以免暴露复杂的、与算法相关的数据结构;
(d) 一个类定义了多种行为,并且为这些行为在这个类的操作中以多个条件语句的形式出现相关的条件分支移入它们各自的Strategy类中,以代替这些语句。 (6)作用
策略模式将类中的算法分离出放在一个单独的类中。不同的算法适用于不同的问题。如果所有的算法都集中在一个类中定会导致带有条件选择的杂乱的代码。策略模式使得客户端能够轻松的从一系列算法中找出适合自己的算法。这些算法可以不依赖他们用到的数据来表示。
(7)代码实现
using System;
using System.Collections.Generic; using System.Linq; using System.Text;
namespace Strategy {
// The Context class Context {
// Context state
public const int start = 5; public int Counter = 5;
// Strategy aggregation
IStrategy strategy = new Strategy1();
// Algorithm invokes a strategy method public int Algorithm() {
return strategy.Move(this); }
// Changing strategies
public void SwitchStrategy() {
if (strategy is Strategy1) strategy = new Strategy2(); else
strategy = new Strategy1(); } }
// Strategy interface interface IStrategy {
int Move (Context c); }
// Strategy 1
class Strategy1 : IStrategy {
public int Move (Context c) {
return ++c.Counter; } }
// Strategy 2
class Strategy2 : IStrategy {
public int Move (Context c) {
return --c.Counter ; } }
class Program {
static void Main(string[] args) {
Context context = new Context(); context.SwitchStrategy(); Random r = new Random(37);
for (int i=Context.start; i<=Context.start+15; i++)
{
if (r.Next(3) == 2) {
Console.Write("|| "); context.SwitchStrategy(); }
Console.Write(context.Algorithm() +" "); }
Console.WriteLine(); Console.ReadLine(); } } }
输出: /* Output
4 || 5 6 7 || 6 || 7 8 9 10 || 9 8 7 6 || 7 || 6 5 */
总结
Strategy模式的要点:
1、Strategy及其子类为组件提供了一系列可重用的算法,从而可以使得类型在运行时方便地根据需要在各个算法之间进行切换。所谓封装算法,支持算法的变化。
2、Strategy模式提供了用条件判断语句以外的另一中选择,消除条件判断语句,就是在解耦合。含有许多条件判断语句的代码通常都需要Strategy模式。
3、Strategy模式以算法为中心,可以和Factory Method联合使用,在工厂中使用配制文件对变化的点进行动态的配置。这样就使变化放到了运行时。 4、Strategy模式集中在算法的封装上
百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说公务员考试软件工程Strategy策略模式(2)在线全文阅读。
相关推荐: