织梦CMS - 轻松建站从此开始!

罗索

设计模式 - Strategy 模式(策略模式)

jackyhwei 发布于 2011-04-14 15:32 点击:次 
Strategy 模式(策略模式) 作用:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换.本模式使得算法可独立于使用它的客户而变化。
TAG:

作用:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换.本模式使得算法可独立于使用它的客户而变化。

UML结构图:

解析: 

简而言之一句话,Strategy模式是对算法的封装.处理一个问题的时候可能有多种算法,这些算法的接口(输入参数,输出参数等)都是一致的,那么可以考虑采用Strategy模式对这些算法进行封装,在基类中定义一个函数接口就可以了.

代码实现:

Strategy.h
 1 
 2 #ifndef STRATEGY_H
 3 #define STRATEGY_H
 4 
 5 class Strategy;
 6 
 7 class Context
 8 {
 9 public:
10     Context(Strategy *pStrategy);
11     ~Context();
12 
13     void ContextInterface();
14 private:
15     Strategy* m_pStrategy;
16 };
17 
18 class Strategy
19 {
20 public:
21     virtual ~Strategy(){}
22 
23     virtual void AlgorithmInterface() = 0;
24 };
25 
26 class ConcreateStrategyA
27     : public Strategy
28 {
29 public:
30     virtual ~ConcreateStrategyA(){}
31 
32     virtual void AlgorithmInterface();
33 };
34 
35 #endif
36
Strategy.cpp
 1 
 2 #include <iostream>
 3 #include "Strategy.h"
 4 
 5 Context::Context(Strategy *pStrategy)
 6     : m_pStrategy(pStrategy)
 7 {
 8 }
 9 
10 Context::~Context()
11 {
12     delete m_pStrategy;
13     m_pStrategy = NULL;
14 }
15 
16 void Context::ContextInterface()
17 {
18     if (NULL != m_pStrategy)
19     {
20         m_pStrategy->AlgorithmInterface();
21     }
22 }
23 
24 void ConcreateStrategyA::AlgorithmInterface()
25 {
26     std::cout << "AlgorithmInterface Implemented by ConcreateStrategyA\n";
27 }
28
Main.cpp
 1 
 2 #include "Strategy.h"
 3 
 4 int main()
 5 {
 6     Strategy* pStrategy = new ConcreateStrategyA();
 7     Context*  pContext  = new Context(pStrategy);
 8 
 9     pContext->ContextInterface();
10 
11     delete pContext;
12 
13     return 0;
14 }
15 

 

(whiteyun)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201104/11212.html]
本文出处:cnblogs.com/whiteyun 作者:whiteyun
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容