【1】什么是适配器模式? 将一个类的接口转换成客户希望的另外一个接口。 Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。 【2】适配器模式的代码示例: 代码示例如下1: #include <iostream> #include <string> using namespace std; class Adaptee { public: virtual void myRequest() { cout << "实际上的接口" << endl; } }; class Target { public: virtual void request() = 0; virtual ~Target(){} }; class Adapter : public Target { private: Adaptee adaptee; public: void request() { adaptee.myRequest(); } }; int main() { Target *target = new Adapter(); target->request(); delete target; return 0; } //Result: //实际上的接口
代码示例如下2: #include <iostream> #include <string> using namespace std; class Player { public: string name; Player(string name) { this->name = name; } virtual void attack() = 0; virtual void defence() = 0; }; class Forwards : public Player { public: Forwards(string name) : Player(name){} void attack() { cout << name << "前锋进攻" << endl; } void defence() { cout << name << "前锋防守" << endl; } }; class Center : public Player { public: Center(string name) : Player(name){} void attack() { cout << name << "中锋进攻" << endl; } void defence() { cout << name << "中锋防守" << endl; } }; class Backwards : public Player { public: Backwards(string name) : Player(name){} void attack() { cout << name << "后卫进攻" << endl; } void defence() { cout << name << "后卫防守" << endl; } }; /*****************************************************************/ class ForeignCenter { public: string name; ForeignCenter(string name) { this->name = name; } void myAttack() { cout << name << "外籍中锋进攻" << endl; } void myDefence() { cout << name << "外籍中锋防守" << endl; } }; /*****************************************************************/ class Translator : public Player { private: ForeignCenter *fc; public: Translator(string name) : Player(name) { fc = new ForeignCenter(name); } void attack() { fc->myAttack(); } void defence() { fc->myDefence(); } }; /*****************************************************************/ int main() { Player *p1 = new Center("李俊宏"); p1->attack(); p1->defence(); Translator *tl = new Translator("姚明"); tl->attack(); tl->defence(); return 0; } //Result: /* 李俊宏中锋进攻 李俊宏中锋防守 姚明外籍中锋进攻 姚明外籍中锋防守 */
http://www.cnblogs.com/Braveliu/p/3946831.html