设计模式 Design Parttern ——匹配器Adapter http://blog.csdn.net/leeidea 1:头文件 #ifndef _ADAPTER_H_VANEY_ #define _ADAPTER_H_VANEY_ #include <iostream> using namespace std; /****************************************************************** 名称 :Adapter.h 版本 :1.00 描述 :演示匹配器的概念 作者 :vaney.li@gmail.com http://blog.csdn.net/leeidea 日期 :2010年10月14日 版权 :vaney.li@gmail.com http://blog.csdn.net/leeidea 参考 :http://www.cnblogs.com/beniao/archive/2008/07/01/1232799.html http://blog.csdn.net/leishiwei/archive/2010/01/08/5158841.aspx ******************************************************************/ /* 官方解释:The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class to an interface expected by the clients. 我的理解:适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而 无法在一起工作的两个类能够在一起工作。 我的应用: */ //转换前的接口 class CInterfaceA { public: virtual void FunctionA() { cout << "FunctionA()" << endl; } }; //转换后的接口 class CInterfaceB { public: virtual void FunctionB() { cout << "FunctionB()" << endl; } }; //匹配器 class CAdapter : public CInterfaceB { CInterfaceA* _a; public: CAdapter(CInterfaceA* a) { _a = a; cout << "CAdapter()" << endl; } virtual ~CAdapter() { if(_a) delete _a; _a = 0; cout << "~CAdapter()" << endl; } public: virtual void FunctionB() { cout << "FunctionB()" << endl; _a->FunctionA(); } }; #define C_API extern "C" //用户 C_API int UsingAD(); #endif 2:源文件 #include "Adapter.h" C_API int UsingAD() { /* 用户在使用接口B的时候,内部其实是调用接口A的方法。实现接口的转换 */ CInterfaceA* a = new CInterfaceA(); CInterfaceB* b = new CAdapter(a); b->FunctionB(); return 1; } 3:用户文件main.c extern int UsingAD(); //系统默认入口 int _tmain(int argc, _TCHAR* argv[]) { return UsingAD(); }