C++设计模式——适配器模式
2022/2/22 12:58:15
本文主要是介绍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)要在双方都不太容易修改的时候再使用适配器模式适配,而不是一有不同是就使用它。
这篇关于C++设计模式——适配器模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享
- 2024-07-05idea控制台,日志太多,导致部分想看得日志被刷走 搜不到-icode9专业技术文章分享
- 2024-07-05The server selected protocol version Tls10 is not accepted by client preferences [TLs12]-icode9专业技术文章分享
- 2024-07-05怎么清理项目缓存-icode9专业技术文章分享
- 2024-07-04安装 Eyoucms详细图文教程-icode9专业技术文章分享
- 2024-07-04ueditor 复制文章时,图片的链接是一个下载图片地址,该如何处理?-icode9专业技术文章分享
- 2024-07-04怎样判断host有没有对wordpress有缓存呢-icode9专业技术文章分享
- 2024-07-04具有编译功能的系统make后,无法ssh连接-icode9专业技术文章分享
- 2024-07-04make后如何升级ssh-icode9专业技术文章分享
- 2024-07-03微信支付提示下单账户与支付账户不一致-icode9专业技术文章分享