Chinaunix首页 | 论坛 | 博客
  • 博客访问: 148437
  • 博文数量: 27
  • 博客积分: 531
  • 博客等级: 一等列兵
  • 技术积分: 332
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-25 18:31
文章分类

全部博文(27)

文章存档

2015年(4)

2014年(3)

2013年(6)

2012年(14)

我的朋友

分类: Delphi

2012-05-20 14:18:43

       闲话少叙,直接切入正题,开始说说策略模式;
       所谓的策略模式,它封装了一族算法,使它们之间可以互相的替换,而对使用算法的用户来说不会受到影响,其实,说不受到影响是指用户代码的模式是一致的,即不用改变使用习惯。
       1.  策略的抽象 Strategy
            1.1. 策略 StrategyA
            1.2. 策略 StrategyB
       2. 上下文环境 Context,对其初始化一个指定的策略,让后启动该环境,则得到预期的结果;这个初始化和
            启动的流程对用户来说是不变的,只是改变初始的具体策略而已,如选则 A 或者 B。
代码实例:
1. strategy.h

点击(此处)折叠或打开

  1. #ifndef _STRATEGY_H_
  2. #define _STRATEGY_H_

  3. class Strategy
  4. {
  5. public:
  6.     virtual void AlgorithmInterface() = 0;
  7. };

  8. #endif
2. strategyA.h

点击(此处)折叠或打开

  1. #ifndef _STRATEGY_A_H_
  2. #define _STRATEGY_A_H_

  3. #include "strategy.h"

  4. class StrategyA : public Strategy
  5. {
  6. public:
  7.     void AlgorithmInterface();
  8. };

  9. #endif
3. strategyA.cpp

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include "strategyA.h"

  3. void StrategyA::AlgorithmInterface()
  4. {
  5.     std::cout << "stategy A be called" << std::endl;
  6. }
4. strategyB.h

点击(此处)折叠或打开

  1. #ifndef _STRATEGY_B_H_
  2. #define _STRATEGY_B_H_

  3. #include "strategy.h"

  4. class StrategyB : public Strategy
  5. {
  6. public:
  7.     void AlgorithmInterface();
  8. };

  9. #endif
5. strategyB.cpp

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include "strategyB.h"

  3. void StrategyB::AlgorithmInterface()
  4. {
  5.     std::cout << "stategy B be called" << std::endl;
  6. }
6. context.h

点击(此处)折叠或打开

  1. #ifndef _CONTEXT_H_
  2. #define _CONTEXT_H_

  3. #include "strategy.h"

  4. class Context
  5. {
  6. public:
  7.     Context(Strategy* s);
  8.     void ContextInterface();

  9. private:
  10.     Strategy* m_ps;
  11. };

  12. #endif
7. context.cpp

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include "context.h"

  3. Context::Context(Strategy* s)
  4. {
  5.     m_ps = s;
  6. }

  7. void Context::ContextInterface()
  8. {
  9.     m_ps->AlgorithmInterface();
  10. }
8. test.cpp

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include "strategy.h"
  3. #include "strategyA.h"
  4. #include "strategyB.h"
  5. #include "context.h"

  6. int main(int argc, char* args[])
  7. {
  8.     Strategy* sa = new StrategyA();
  9.     Strategy* sb = new StrategyB();
  10.     Context ca(sa);
  11.     Context cb(sb);

  12.     ca.ContextInterface();
  13.     cb.ContextInterface();

  14.     delete sa;
  15.     delete sb;
  16. }
执行结果:

点击(此处)折叠或打开

  1. ./test
  2. stategy A be called
  3. stategy B be called
       发现,策略模式 和 简单工厂 以及 工厂方法 有很大的相似性,可以说是二者的一个结合品;这里的策略如
同产品,工厂如同环境,只不过,策略模式送入的是真正的策略,而简单工厂送入的是说明;而工厂方法留给
用户选择的则是具体的 creator,不同的 creator 生产不同的产品。
       好了,就说这么多,欢迎拍砖 ^-^
阅读(1780) | 评论(0) | 转发(0) |
0

上一篇:工厂方法

下一篇:原型模式

给主人留下些什么吧!~~