C++设计模式——适配器模式
适配器模式:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原来由于接口不兼容而不能一起工作的那些类可以一起工作。
角色:
(1)Target:这是客户所期待的接口,Target可以是具体的或抽象的类,也可以是接口。
(2)Adaptee:需要适配的类。
(3)Adapter:通过在内部包装一个Adaptee对象,把源接口转换成目标接口。
#include <iostream> using namespace std; //球员 class Player { protected: string name; public: Player(string name):name(name){} virtual void Attack() = 0; virtual void Defense() = 0; virtual~Player() {} }; //前锋 class Forwards : public Player { public: Forwards(string name):Player(name){} virtual void Attack() { cout << "前锋" << name << "进攻" << endl; } virtual void Defense() { cout << "前锋" << name << "防守" << endl; } }; //中锋 class Center : public Player { public: Center(string name) :Player(name) {} virtual void Attack() { cout << "中锋" << name << "进攻" << endl; } virtual void Defense() { cout << "中锋" << name << "防守" << endl; } }; //后卫 class Guards : public Player { public: Guards(string name) :Player(name) {} virtual void Attack() { cout << "后卫" << name << "进攻" << endl; } virtual void Defense() { cout << "后卫" << name << "防守" << endl; } }; class ForeignCenter { public: void SetName(string name) { this->name = name; } string GstName() { return name; } void ForeignAttack() { cout << "外籍中锋 " << name << " 攻击" << endl; } void ForeignDefense() { cout << "外籍中锋 " << name << " 防守" << endl; } private: string name; }; //适配器类 翻译者 class Translator :public Player { public: Translator(string name) :Player(name) { ym = new ForeignCenter; ym->SetName(name); } ~Translator() { if (ym != NULL) delete ym; } void Attack() { //翻译者将Attack 翻译成 ForeignAttack ym->ForeignAttack(); } void Defense() { ym->ForeignDefense(); //翻译者将Defense 翻译成 ForeignDefense } private: ForeignCenter* ym; //外籍中锋 }; int main() { Player* b = new Forwards("巴蒂尔"); b->Attack(); Player* c = new Guards("麦克格雷迪"); c->Attack(); Player* ym = new Translator("姚明"); //姚明问: "Attack和Defense是什么意思?" ym->Attack(); ym->Defense(); system("pause"); return 0; }
使用场景:
什么时候用?
(1)在想使用一个已存在的类,但是如果他的接口,也就是它的方法和你的要求不相同时,就应该考虑用适配器模式。
(2)用了适配器模式,客户代码可以统一调用统一接口就行了,这样可以更简单,更直接,更紧凑。
(3)要在双方都不太容易修改的时候再使用适配器模式适配,而不是一有不同是就使用它。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧