6.设计模式名称:适配器(Adapter)
概念
适配器模式是一种结构型设计模式,它允许不兼容的接口之间进行交互。适配器充当两个不兼容的接口之间的桥梁,通过将一个类的接口转换成另一个类期望的接口来工作。
意图
- 使原本由于接口不兼容而不能一起工作的那些类可以一起工作。
- 封装可能需要在未来改变的代码。
适用性
- 当你想使用一个已经存在的类,而其接口不符合你的需求时。
- 当你想创建一个可重用的类,该类可以与不相关或不可预见的类(即那些接口可能不一定兼容的类)协同工作。
- 当你需要使用几个现有的子类,但是子类化每个类以适配它们的接口不实际的或不可行的时候。
结构
适配器模式主要包括三个角色:
- Target:定义客户期望使用的特定领域相关的接口。
- Adapter:适配器类负责将 Target 接口转换为 Adaptee 接口的实现。
- Adaptee:一个已存在的接口,通常能完成所需的功能,但接口与客户的接口不兼容。
类适配器使用多重继承对一个接口与另一个接口进行匹配
对象匹配器依赖于对象组合
实现代码示例
以下是使用 C++ 实现适配器模式的一个示例,展示了如何使两个不兼容的类可以一起工作。
#include <iostream>
// Target Interface
class RoundHole {
public:
virtual bool fits(double radius) const = 0;
virtual ~RoundHole() {}
};
// Adaptee
class SquarePeg {
private:
double width;
public:
SquarePeg(double w) : width(w) {}
double getWidth() const {
return width;
}
};
// Adapter
class SquarePegAdapter : public RoundHole {
private:
SquarePeg& peg;
public:
SquarePegAdapter(SquarePeg& p) : peg(p) {}
bool fits(double radius) const override {
double halfWidth = peg.getWidth() / 2;
return (halfWidth * sqrt(2)) <= radius;
}
};
// Client code
int main() {
SquarePeg smallPeg(5);
SquarePeg largePeg(10);
SquarePegAdapter smallPegAdapter(smallPeg);
SquarePegAdapter largePegAdapter(largePeg);
std::cout << "A small peg " << (smallPegAdapter.fits(5) ? "fits" : "does not fit") << " in the hole." << std::endl;
std::cout << "A large peg " << (largePegAdapter.fits(5) ? "fits" : "does not fit") << " in the hole." << std::endl;
return 0;
}
在这个例子中,RoundHole
类是目标接口,而 SquarePeg
是一个已存在的类,其接口不兼容。SquarePegAdapter
类是适配器,它允许将 SquarePeg
的接口适配为 RoundHole
接口。适配器通过计算适合圆孔的最大正方形边长来适配接口。
输出
A small peg fits in the hole.
A large peg does not fit in the hole.
特点与考虑
- 适配器模式可以帮助系统独立于它使用的外部类或库,增加了系统的灵活性和可扩展性。
- 适配器使得代码更加复杂,尤其是在处理多个特殊的适配器时。这可能会使代码难以理解和维护。