C++ 适配器模式
2021/6/2 12:20:58
本文主要是介绍C++ 适配器模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
什么是适配器模式?
适配器它是主要作用是将一个类的接口转换成客户希望的另外一个接口这样使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
适配器模式有两种:1.类的适配器 2.对象适配器,对象适配器更多一些。
代码示例
#includeusing namespace std; //目标接口 class CTarget { public: CTarget() {} virtual ~CTarget() {} virtual void Request() = 0; }; //现存类 class CAdeptee { public: CAdeptee() {} ~CAdeptee() {} //执行请求任务 void SpecificalRequest() { cout << "原始类方法被调用" << endl; } }; //类模式:适配器类 class CAdapter :public CTarget { public: CAdapter() { pAdeptee = new CAdeptee(); } ~CAdapter() { delete pAdeptee; }; //目标接口,将实际接口和目标接口的差异进行封装 virtual void Request() { cout << "类模式适配器:"; pAdeptee->SpecificalRequest(); } private: CAdeptee* pAdeptee; }; //对象模式,适配器类,继承CTarget类,采用组合的方式实现Adaptee的复用 class CAdapter1 :public CTarget { public: CAdapter1(CAdeptee* adaptee) { m_Adaptee = new CAdeptee(); } CAdapter1() {} ~CAdapter1() { if (m_Adaptee != NULL) { delete m_Adaptee; } } //实现Target定义的Request接口 void Request() { cout << "对象模式模式适配器:"; m_Adaptee->SpecificalRequest(); } private: CAdeptee* m_Adaptee; }; int main() { //以多态的方式,目标类对象指针接收派生的适配器类对象 CTarget* pTarget = new CAdapter(); pTarget->Request(); CTarget* pTarget1 = new CAdapter1(); pTarget1->Request(); delete pTarget; delete pTarget1; return 0; }
类模式适配器:原始类方法被调用 对象模式模式适配器:原始类方法被调用
适配器模式的优点:
(1) 将目标类和适配者类解耦,通过引入一个适配器类来重用现有的适配者类,无须修改原有结构。
(2) 增加了类的透明性和复用性,将具体的业务实现过程封装在适配者类中,对于客户端类而言是透明的,而且提高了适配者的复用性,同一个适配者类可以在多个不同的系统中复用
这篇关于C++ 适配器模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding
- 2024-06-23AI大模型企业应用实战(15)-langchain核心组件
- 2024-06-23AI大模型企业应用实战(16)-langchain核心组件
- 2024-06-23AI 大模型企业应用实战(06)-初识LangChain
- 2024-06-19EntBot.ai: AI Website Chatbot for Product Guides and Development Doc
- 2024-06-17zero-shot-learning-definition-examples-comparison
- 2024-06-06Package Easy(基于 NSIS 的打包exe安装包工具)使用方法-icode9专业技术文章分享
- 2024-06-06基于 casdoor 的 ELK 开源登录认证解决方案: elk-auth-casdoor-icode9专业技术文章分享
- 2024-05-29Elasticsearch慢查询日志配置