设计模式 - Strategy 模式(策略模式)
作用:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换.本模式使得算法可独立于使用它的客户而变化。
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
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
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
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