设计模式_09 适配器模式
9 适配器模式
9.1 概述
将一个类的接口转换成客户希望的另一个接口,使得原本由于接口不兼容不能一起工作的类可以协同工作。
适配器模式分为类适配器模式和对象适配器模式。
9.2 结构
目标接口:当前系统业务所期待的接口,可以是抽象类或接口。
适配者类:被访问和适配的现存组件库中的组件的接口。
适配器类:转换器。
9.3 实现
9.3.1 类适配器模式实现
9.3.1.1 UML图
9.3.1.2 代码
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
class Typec {
protected:
string typecContext;
public:
virtual void readTypec() = 0;
virtual void writeTypec() = 0;
};
class TypecRead : public Typec {
public :
void readTypec() {
cout << this->typecContext << endl;
}
void writeTypec() {
this->typecContext = "Type-C";
}
};
class Usb {
protected:
string usbContext;
public:
virtual void readUsb() = 0;
virtual void writeUsb() = 0;
};
class UsbRead : public Usb {
public:
void readUsb() {
cout << this->usbContext << endl;
}
void writeUsb() {
this->usbContext = "直连USB";
}
};
class TypecAdapterUsb : public Usb, public TypecRead{
public:
void readUsb() {
writeUsb();
cout << "USB转接:" << this->usbContext << endl;
}
void writeUsb() {
this->usbContext = this->typecContext;
}
};
class Computer {
public:
void readUsb(Usb* usb) {
usb->readUsb();
}
};
int main() {
TypecAdapterUsb* typecAdapterUsb = new TypecAdapterUsb();
typecAdapterUsb->writeTypec();
Computer* computer = new Computer();
computer->readUsb(typecAdapterUsb);
return 0;
}
9.3.2 对象适配器模式实现
9.3.2.1 UML图
9.3.2.2 代码
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
class Typec {
protected:
string typecContext;
public:
virtual string readTypec() = 0;
virtual void writeTypec() = 0;
};
class TypecRead : public Typec {
public:
string readTypec() {
return this->typecContext;
}
void writeTypec() {
this->typecContext = "Type-C";
}
};
class Usb {
protected:
string usbContext;
public:
virtual string readUsb() = 0;
virtual void writeUsb() = 0;
};
class UsbRead : public Usb {
public:
string readUsb() {
return this->usbContext;
}
void writeUsb() {
this->usbContext = "直连USB";
}
};
class TypecAdapterUsb : public Usb {
private:
Typec* typec = new TypecRead();
public:
string readUsb() {
return this->usbContext;
}
void writeUsb() {
typec->writeTypec();
this->usbContext = typec->readTypec();
}
};
class Computer {
public:
string readUsb(Usb* usb) {
return usb->readUsb();
}
};
int main() {
TypecAdapterUsb* typecAdapterUsb = new TypecAdapterUsb();
typecAdapterUsb->writeUsb();
Computer* computer = new Computer();
cout <<computer->readUsb(typecAdapterUsb) <<endl;
UsbRead* useRead = new UsbRead();
useRead->writeUsb();
cout << computer->readUsb(useRead) << endl;
return 0;
}
9.4 使用场景
以前开发的系统存在满足新系统功能需求的类,但其接口同新系统不一致。
使用第三方提供的组件,但组件接口定义和自己要求的接口定义不同。