博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
适配器模式
阅读量:6826 次
发布时间:2019-06-26

本文共 2449 字,大约阅读时间需要 8 分钟。

【1】什么是适配器模式?将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。【2】适配器模式的代码示例:代码示例如下1:#include 
#include
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 
#include
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

你可能感兴趣的文章