一、定义
适配器模式:将一个类的借口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。
二、模式结构
适配器模式包含如下角色:
- Target:目标抽象类
- Adapter:适配器类
- Adaptee:适配者类
- Client:客户类
适配器模式有对象适配器和类适配器两种实现:
对象适配器:
类适配器:
三、代码样例
#include#include "Adapter.h"#include "Adaptee.h"#include "Target.h"using namespace std;int main(int argc, char *argv[]){ Adaptee * adaptee = new Adaptee(); Target * tar = new Adapter(adaptee); tar->request(); return 0;}
///// Adapter.h// Implementation of the Class Adapter// Created on: 03-十月-2014 17:32:00// Original author: colin///#if !defined(EA_BD766D47_0C69_4131_B7B9_21DF78B1E80D__INCLUDED_)#define EA_BD766D47_0C69_4131_B7B9_21DF78B1E80D__INCLUDED_#include "Target.h"#include "Adaptee.h"class Adapter : public Target{public: Adapter(Adaptee *adaptee); virtual ~Adapter(); virtual void request();private: Adaptee* m_pAdaptee;};#endif // !defined(EA_BD766D47_0C69_4131_B7B9_21DF78B1E80D__INCLUDED_)
///// Adapter.cpp// Implementation of the Class Adapter// Created on: 03-十月-2014 17:32:00// Original author: colin///#include "Adapter.h"Adapter::Adapter(Adaptee * adaptee){ m_pAdaptee = adaptee;}Adapter::~Adapter(){}void Adapter::request(){ m_pAdaptee->specificRequest();}
///// Adaptee.h// Implementation of the Class Adaptee// Created on: 03-十月-2014 17:32:00// Original author: colin///#if !defined(EA_826E6B4F_12BE_4609_A0A3_95BD5E657D36__INCLUDED_)#define EA_826E6B4F_12BE_4609_A0A3_95BD5E657D36__INCLUDED_class Adaptee{public: Adaptee(); virtual ~Adaptee(); void specificRequest();};#endif // !defined(EA_826E6B4F_12BE_4609_A0A3_95BD5E657D36__INCLUDED_)
运行结果: