c++ 设计模式之适配器模式
来源:互联网 发布:和孩子一起学编程 pdf 编辑:程序博客网 时间:2024/06/03 19:29
Adapter适配器模式
作用:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
分为类适配器模式和对象适配器模式。
系统的数据和行为都正确,但接口不符时,我们应该考虑使用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。
想使用一个已经存在的类,但如果它的接口,也就是它的方法和你的要求不相同时,就应该考虑用适配器模式。
比如购买的第三方开发组件,该组件接口与我们自己系统的接口不相同,或者由于某种原因无法直接调用该组件,可以考虑适配器。
UML图如下:
图1:类模式适配器
对象模式适配器
下面给出类适配器模式和对象适配器模式的实例:
#include"stdafx.h"#include<iostream>using namespace std;//目标客户类,客户需要的接口class Target{public:Target(){}~Target(){}virtual void Request() {cout << "Target::Request()" << endl;}};class Adaptee //需要的适配器类,对Target的接口进行处理,{public:Adaptee(){}~Adaptee(){}void SpecificRequest(){ cout << "Adaptee::SpecificRequest()" << endl;}};//类适配器模式 ,通过public继承获得接口,通过 private继承获得实现class Adapter :public Target,private Adaptee{public:Adapter(){}~Adapter(){}void Request(){cout << "Adapter::Request()" << endl;this->SpecificRequest();cout << "----------------------------" <<endl;}};//对象适配器模式class Adapter1:public Target{public:Adapter1(Adaptee* adaptee){m_Adaptee = adaptee;}Adapter1(){m_Adaptee = new Adaptee();}~Adapter1(){}void Request(){cout << "Adapter1::Request()" << endl;if(m_Adaptee != NULL){m_Adaptee->SpecificRequest();}cout << "***********************" <<endl;}private:Adaptee * m_Adaptee;};
// client 代码
// AdapterMode.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include"Adapter.hpp"int _tmain(int argc, _TCHAR* argv[]){#if 0//类模式适配器Target *p = new Adapter();p->Request();//对象模式适配器Adaptee *ade = new Adaptee();Target *p1 = new Adapter1(ade);p1->Request();#endif// 对象模式适配;Target *p2= new Adapter1();p2->Request();system("pause");return 0;}
0 0
- C#--设计模式之适配器模式
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式 之 适配器
- 设计模式 之 适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式 之 适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- UE4:BindUObject,BindLambda
- 代码调试
- Android产品研发(五)-->多渠道打包
- 28、SSH框架-Spring+Mybatis+Maven+MySql搭建实例(3)
- UBUNTU加SAMBA
- c++ 设计模式之适配器模式
- 欢迎使用CSDN-markdown编辑器
- xcode开发:mach_msg_trap异常处理
- Android产品研发(六)-->Apk混淆
- HIVE学习与实践(一):基本命令
- AndroidStudio 中 ctrl + 左键 进入源码看不到详细代码
- 我自己的读入优化
- 友盟安卓推送的“多包名”使用方式解决R文件报错问题
- eclipse下生成Java类图和时序图,生成UML图(更完整版)