目录
适配器模式(Adapter Pattern)是一种结构型设计模式,用于解决接口不兼容的问题。当两个原本不兼容的类需要协同工作时,适配器模式通过创建一个中间层(适配器)来转换接口,使它们能够无缝协作。这种模式在遗留系统集成、第三方库对接等场景中尤为常见。
一、模式核心概念与结构
适配器模式包含三个核心角色:
- 目标接口(Target):客户端期望的接口。
- 适配者(Adaptee):需要被适配的现有接口。
- 适配器(Adapter):连接目标接口和适配者的中间层,负责接口转换。
适配器模式有两种实现方式:类适配器(通过继承实现)和对象适配器(通过组合实现)。在 C++ 中,对象适配器更常用,因为它避免了多重继承的复杂性。
二、对象适配器实现示例
以下是一个将圆接口适配为矩形接口的经典示例:
#include <iostream>
#include <cmath>
// 目标接口:客户端期望的矩形接口
class Rectangle
{
public:
virtual ~Rectangle() {
}
virtual void draw(int x, int y, int width, int height) = 0;
};
// 适配者:现有的圆接口
class Circle {
public:
void drawCircle(int x, int y, int radius)
{
std::cout << "Drawing circle at (" << x << ", " << y
<< ") with radius " << radius << std::endl;
}
};
// 对象适配器:将圆适配为矩形接口
class CircleAdapter : public Rectangle
{
private:
Circle circle; // 组合适配者对象
public:
// 实现目标接口的draw方法,转换为圆的绘制逻辑
void draw(int x, int y, int width, int height) override
{
// 假设矩形的宽高相等时视为圆形(简化逻辑)
int radius = width / 2;
if (height == width)
{
circle.drawCircle(x + radius, y + radius, radius);
} else
{
std::cout << "Invalid rectangle for circle adaptation" << std::endl;
}
}
};
// 客户端代码
int main()
{
// 使用适配器替代原生矩形接口
Rectangle* adapter =