1、动机
让接口不兼容的对象能够相互合作。
小栗子:
-
你在开发一款股票市场监测程序,它会从不同来源下载 XML 格式的股票数据,但现在想在程序中整合一个只兼容JSON格式的函数库,怎么办?
-
解决方案:创建一个适配器。这是一个特殊的对象,能够转换对象接口,使其能与其他对象进行交互。
2、结构
适配器模式包含如下角色:
- Target:目标抽象类
- Adapter:适配器类
- Adaptee:适配者类
- Client:客户类
适配器模式有对象适配器和类适配器两种实现:对象适配器和类适配器。
2.1 对象适配器
实现时使用了构成原则:适配器实现了其中一个对象的接口,并对另一个对象进行封装。
- 客户端(Client)是包含当前程序业务逻辑的类。
- 客户端接口(Client Interface) 描述了其他类与客户端代码合作时必须遵循的协议。
- 服务(Service)中有一些功能类(通常来自第三方或遗留系统)。客户端与其接口不兼容,因此无法直接调用其功能。
- 适配器(Adapter) 是一个可以同时与客户端和服务交互的类:它在实现客户端接口的同时封装了服务对象。适配器接受客户端通过适配器接口发起的调用,并将其转换为适用于被封装服务对象的调用。
- 客户端代码只需通过接口与适配器交互即可,无需与具体的适配器类耦合。因此,你可以向程序中添加新类型的适配器而无需修改已有代码。这在服务类的接口被更改或替换时很有用:你无需修改客户端代码就可以创建新的适配器类。
2.2 类适配器
这一实现使用了继承机制:适配器同时继承两个对象的接口。请注意, 这种方式仅能在支持多重继承的编程语言中实现,例如 C++。
3、对象适配器时序图
4、对象适配器代码
ClientInterface.h:
#ifndef CLIENT_INTERFACE_H_
#define CLIENT_INTERFACE_H_
// 圆钉:客户端接口,在c++中定义为抽象基类
class RoundPeg
{
public:
RoundPeg(){}
virtual int get_radius() = 0;
};
#endif //CLIENT_INTERFACE_H_
Adapter.h:
#ifndef ADAPTER_H_
#define ADAPTER_H_
#include <cmath>
#include "ClientInterface.h"
#include "Service.h"
//方钉适配器:该适配器能让客户端将方钉放入圆孔中
class SquarePegAdapter :public RoundPeg
{
public:
explicit SquarePegAdapter(SquarePeg* sp):square_peg_(sp){}
int get_radius() override
{
return square_peg_->get_width()*sqrt(2)/2;
}
private:
SquarePeg* square_peg_;
};
#endif //ADAPTER_H_
Service.h:
#ifndef SERVICE_H_
#define SERVICE_H_
// 方钉:适配者类,即和客户端不兼容的类
class SquarePeg
{
public:
//将构造函数声明为explicit来阻止构造函数定义的隐式类类型转换
explicit SquarePeg(int w):width_(w){}
int get_width()
{
return width_;
}
private:
int width_;
};
#endif //SERVICE_H_
Client.h:
#ifndef CLIENT_H_
#define CLIENT_H_
#include"ClientInterface.h"
//圆孔:客户端类
class RoundHole
{
public:
explicit RoundHole(int r):radius_(r){}
int get_radius()
{
return radius_;
}
bool isFit(RoundPeg* rp)
{
return radius_ >= rp->get_radius();
}
private:
int radius_;
};
#endif //CLIENT_H_
main.cpp:
#include<iostream>
#include "Client.h"
#include "Adapter.h"
int main()
{
//b=半径为10的圆钉
RoundHole* hole = new RoundHole(10);
//半径分别为5和20的大小方钉 + 它们的适配器
SquarePeg* small_square_peg = new SquarePeg(5);
SquarePeg* large_square_peg = new SquarePeg(20);
SquarePegAdapter* small_square_peg_adapter = new SquarePegAdapter(small_square_peg);
SquarePegAdapter* large_square_peg_adapter = new SquarePegAdapter(large_square_peg);
if(hole->isFit(small_square_peg_adapter))
{
std::cout<<"small square peg fits the hole"<<std::endl;
}
else std::cout<<"small square peg don't fits the hole"<<std::endl;
if(hole->isFit(large_square_peg_adapter))
{
std::cout<<"large square peg fits the hole"<<std::endl;
}
else std::cout<<"large square peg don't fits the hole"<<std::endl;
return 0;
}