C++设计模式3————(策略模式)
来源:互联网 发布:八爪鱼软件 编辑:程序博客网 时间:2024/06/03 22:00
策略模式
1.概述
策略模式是将算法的不同实现封装到一个类里面,将算法的实现和算法的使用分离。在算法发生变化时不会影响算法的调用者。在需要不同算法时,可以相互替换,而不影响使用者。
下面是UML图:
2.C++代码实现:
以下是策略基类和子类:
#ifndef BASESTRATEGYINTERFACE_H#define BASESTRATEGYINTERFACE_Hclass BaseStrategyInterface{public: BaseStrategyInterface();public: virtual void AlgorithmFunction()=0;};#endif // BASESTRATEGYINTERFACE_H
<pre name="code" class="cpp">#ifndef STRATEGYA_H#define STRATEGYA_H#include "basestrategyinterface.h"class StrategyA : public BaseStrategyInterface{public: StrategyA();public: void AlgorithmFunction();};#endif // STRATEGYA_H#include "strategya.h"#include <iostream>using namespace std;StrategyA::StrategyA(){}void StrategyA::AlgorithmFunction(){ cout << "Strategy A" << endl;}
<pre name="code" class="cpp">#ifndef STRATEGYB_H#define STRATEGYB_H#include "basestrategyinterface.h"class StrategyB : public BaseStrategyInterface{public: StrategyB();public: void AlgorithmFunction();};#endif // STRATEGYB_H#include "strategyb.h"#include <iostream>using namespace std;StrategyB::StrategyB(){}void StrategyB::AlgorithmFunction(){ cout << "Strategy B" << endl;}
<pre name="code" class="cpp">#ifndef STRATEGYC_H#define STRATEGYC_H#include "basestrategyinterface.h"class StrategyC : public BaseStrategyInterface{public: StrategyC();public: void AlgorithmFunction();};#endif // STRATEGYC_H#include "strategyc.h"#include <iostream>using namespace std;StrategyC::StrategyC(){}void StrategyC::AlgorithmFunction(){ cout << "Strategy C" << endl;}
#ifndef REPLACE_H#define REPLACE_H#include "basestrategyinterface.h"#include <iostream>class Replace{private: BaseStrategyInterface *m_Instance;public: Replace(BaseStrategyInterface *strategy) { m_Instance = strategy; } ~Replace() { if(m_Instance != NULL) { delete m_Instance; } }public: void Algorithm() { m_Instance->AlgorithmFunction(); }};#endif // REPLACE_H调用策略方法:
Replace *replaceA = new Replace(new StrategyA());replaceA->Algorithm();delete replaceA;Replace *replaceB = new Replace(new StrategyB());replaceB->Algorithm();delete replaceB;Replace *replaceC = new Replace(new StrategyC());replaceC->Algorithm();delete replaceC;输出:
Strategy A
Strategy B
Strategy C
以上是策略模式的最简单实现方式,也可以使用其他实现方式,其根本思想不变。
0 0
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式(1)—策略模式
- 设计模式—策略模式(二)
- 设计模式——策略设计模式
- 设计模式——策略模式(行为型模式)
- 常用设计模式(六)——策略设计模式
- Java设计模式—策略
- windows bat 批处理脚本基本用法
- 设置 Apache 文件根目录 和 设置Apache 虚拟目录(Virtual Directory)
- class.forname().newInstance()
- MFC俄罗斯方块
- JUnit 测试spring项目
- C++设计模式3————(策略模式)
- vim配置及插件安装管理(超级详细)
- oracle表空间与数据文件
- C++算法之 合并两个数组
- 24小时格式时间显示有关问题
- Hessian
- Servlet的url-pattern匹配规则
- PL/SQL中复制中文再粘贴出现乱码问题的解决
- wbs简单介绍以及相关模板截图