简介
适配器模式(Adapter Pattern)是一种结构型设计模式,它允许将一个类的接口转换成客户端所期望的另一个接口。适配器模式通常用于解决接口不兼容的问题。
适配器模式的优点
兼容性:将不兼容的接口转换为兼容的接口。
复用性:可以复用现有的类,而无需修改其代码。
灵活性:适配器可以动态地替换现有类的实现。
适配器模式的缺点
1、第三者桥梁作为适配器会带来额外的开销。
2、对开发者或维护者来说,理解代码的难度加大了。
使用场景示例
假设我们有一个现成的类 LegacyRectangle,它提供了一个计算面积的接口,但接口形式不符合我们的需求。我们希望使用一个统一的接口 Shape,其中的 area() 方法可以直接调用。为此,我们引入一个适配器类 RectangleAdapter,将 LegacyRectangle 的接口适配为 Shape 的接口。
代码实现
#include <iostream>
// 目标接口:统一形状接口
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0; // 计算面积
};
// 现有的类:LegacyRectangle
class LegacyRectangle {
public:
LegacyRectangle(double x1, double y1, double x2, double y2)
: x1(x1), y1(y1), x2(x2), y2(y2) {}
// 现有的计算方法
double calculateArea() const {
return (x2 - x1) * (y2 - y1);
}
private:
double x1, y1, x2, y2; // 矩形对角线的两个点
};
// 适配器类:将 LegacyRectangle 适配为 Shape 接口
class RectangleAdapter : public Shape {
public:
RectangleAdapter(double x1, double y1, double x2, double y2)
: legacyRectangle(x1, y1, x2, y2) {}
// 实现目标接口
double area() const override {
return legacyRectangle.calculateArea(); // 调用现有类的方法
}
private:
LegacyRectangle legacyRectangle; // 适配器内部包含现有类的对象
};
// 客户端代码
int main() {
// 使用适配器
Shape* shape = new RectangleAdapter(0, 0, 10, 20);
std::cout << "Area: " << shape->area() << std::endl;
delete shape;
return 0;
}
代码解析
1、目标接口 (Shape):
定义了一个纯虚函数 area(),表示计算面积的统一接口。
2、现有类 (LegacyRectangle):
提供了一个计算面积的方法 calculateArea(),但其接口名称和调用方式与目标接口不一致。
3、适配器类 (RectangleAdapter):
继承自 Shape,内部包含一个 LegacyRectangle 对象。
在 area() 方法中,调用 LegacyRectangle 的 calculateArea(),将现有的接口适配为目标接口。
4、客户端代码:
使用 Shape 接口调用 area(),而无需关心底层是 LegacyRectangle 还是其他类。
输出结果
运行上述代码后,输出为:
Area: 200