Design pattern -- Adapter 发表于 2010-05-03 | 更新于: 2017-10-12 | | 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596// Adapter.cpp : Defines the entry point for the console application.// author: chillyc// email: chillycreator @t gmail.com#include<iostream>#include<string>using namespace std;/// adapter pattern is used for combining two or more classes,/// which have the same behaviors but different interfaces./// some classes is common used in future, and the other which are special will never used./// common used classes should be public, and the other is private./// some classes which inherit adapter class will never use the special ones. /// adapter pattern is divided into two patterns./// one is belong to class structure, and the other is belong to object structure.#ifndef INTERFACEA_H#define INTERFACEA_H/// Interface A is a common interface!class Interface_A{public : virtual void connect_com();};#endifvoid Interface_A::connect_com(){ cout<<"connect a"<<endl;}#ifndef INTERFACEB_H#define INTERFACEB_H/// Interface B is not a common interface, /// it will be used in some special area!class Interface_B{public : virtual void connect_B();};#endifvoid Interface_B::connect_B(){ cout<< "connect b"<<endl;}#ifndef ADAPTERCLASS_H#define ADAPTERCLASS_H/// this class uses private inheritance to construct adapter./// and it is a kind of class structure.class Adapter_Class: public Interface_A, private Interface_B{public: Adapter_Class(); ~Adapter_Class(); virtual void connect();};/// this class uses private member variable to construct adapter./// and it uses object relationship.class Adapter_Object: public Interface_A{private: Interface_B * b;public: Adapter_Object(); ~Adapter_Object(); virtual void connect();};#endifAdapter_Class::Adapter_Class(){ cout<< "Adapter_Class construct"<<endl;}Adapter_Class::~Adapter_Class(){}void Adapter_Class::connect(){ Interface_A::connect_com(); Interface_B::connect_B();}Adapter_Object::Adapter_Object(){ cout<<"Adapter_Object construct"<<endl; b = new Interface_B();}Adapter_Object::~Adapter_Object(){ delete b;}void Adapter_Object::connect(){ Interface_A::connect_com(); b->connect_B();}int main(){ Adapter_Class ac; ac.connect(); Adapter_Object ao; ao.connect(); return 0;} 本文作者: 帐前卒 本文链接: http://chillyc.info/2010/2010-05-03-design-pattern-adapter/ 版权声明: 本博客所有文章除特别声明外,只能复制超链接地址,且必须注明出处!