设计模式 Design Parttern ——策略模式Strategy

设计模式 Design Parttern ——策略模式Strategy

http://blog.csdn.net/leeidea/

 

1:头文件

 

#ifndef _STRATEGY_H_VANEY_ #define _STRATEGY_H_VANEY_ #include using namespace std; /****************************************************************** 名称 :Strategy.h 版本 :1.00 描述 :演示策略模式的概念 作者 :[email protected] http://blog.csdn.net/leeidea 日期 :2010年10月22日 版权 :[email protected] http://blog.csdn.net/leeide ******************************************************************/ /* 官方解释:A Strategy defines a set of algorithms that can be used interchangeably. 我的理解:提供一组算法组,该算法组的算法实现同一个目的,可以替换,注意与Bridge模式区别, 桥模式也是提供一个统一接口和一组不同的实现接口,统一接口具体调用哪个实现接口是 在程序运行中决定的。 */ //抽象解码算法 class CDecode { public: CDecode() { cout << "CDecode()" << endl; } virtual ~CDecode() { cout << "~CCalculate()" << endl; } public: //需要子类实现的方法 virtual void DecodeH264() = 0; }; //硬解码算法 class CHardDecode : public CDecode { public: CHardDecode() { cout << "CHardDecode()" << endl; } virtual ~CHardDecode() { cout << "~CHardDecode()" << endl; } public: virtual void DecodeH264() { cout << "CHardDecode DecodeH264" << endl; } }; //软解码算法 class CSoftDecode : public CDecode { public: CSoftDecode() { cout << "CSoftDecode()" << endl; } virtual ~CSoftDecode() { cout << "~CSoftDecode()" << endl; } public: virtual void DecodeH264() { cout << "CSoftDecode DecodeH264" << endl; } }; //H264解码使用过程 class CProcessH264 { CDecode* _decode; public: CProcessH264(CDecode* decode) { _decode = decode; cout << "CProcessH264(Parameter)" << endl; } CProcessH264() { cout << "CProcessH264()" << endl; } virtual ~CProcessH264() { if(_decode) delete _decode; _decode = 0; cout << "~CProcessH264()" << endl; } public: void SetDecoder(CDecode* decode) { _decode = decode; cout << "SetCalculate" << endl; } void Decode() { cout << "Decode" << endl; if(_decode) return _decode->DecodeH264(); } }; #define C_API extern "C" //用户 C_API int UsingSG(); #endif

2:源文件

 

#include "Strategy.h" C_API int UsingSG() { //创建解码算法 CSoftDecode* decode1 = new CSoftDecode(); CHardDecode* decode2 = new CHardDecode(); //初始为软解码 CProcessH264* process = new CProcessH264(decode1); process->Decode(); //提高效率,改成硬解码 process->SetDecoder(decode2); process->Decode(); return 1; }

3:用户文件main.c

 

extern int UsingSG(); //系统默认入口 int _tmain(int argc, _TCHAR* argv[]) { return UsingSG(); }

你可能感兴趣的:(设计模式)