中文名:适配器模式
作用
GOF中的描述:将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
描述的解释:两个不接口不同但功能相似的产品,转换为一种接口的形式。
优缺点
- 使其使用方式相似
- 改造的成本可能会很高,改造前需评估是否确实需要适配
结构
适配分为两种,一种是类适配器,利用继承的技术;另一种是对象适配器,使用组合的技术。
Target类:目标接口
Adaptee类:带适配的类
Adapter类:将Adaptee类适配后的类
例子
结构中,Shape为Target类,TextView是待适配的类,TextShape是适配后的类。适配后调用方式与Shape类非常接近。
// StructureMode_Adapter.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
struct Coord
{
double x = 0;
};
struct Point
{
double x = 0;
double y = 0;
Point(Coord _x, Coord _y)
{
x = _x.x;
y = _y.x;
}
};
class Manipulator {};
class Shape {
public:
Shape() {}
virtual void BoundingBox(Point& bottomLeft, Point& topRight)
{
}
virtual Manipulator* CreateManipulator() const {
return new Manipulator();
}
};
class TextView {
public:
TextView() {}
void GetOrigin(Coord& x, Coord& y) const {
}
void GetExtent(Coord& width, Coord& height) const {
}
virtual bool IsEmpty() const {
return false;
}
};
// Adapter
class TextShape : public Shape, private TextView {
public:
TextShape() {}
virtual void BoundingBox(Point& bottomLeft, Point& topRight)
{
Coord bottom, left, width, height;
GetOrigin(bottom, left);
GetExtent(width, height);
bottomLeft = Point(bottom, left);
topRight = Point(bottom, left);
}
virtual bool IsEmpty() const {
return TextView::IsEmpty();
}
virtual Manipulator* CreateManipulator() const {
return new Manipulator();
}
private:
};
int main()
{
TextShape textShape;
}
Github链接:https://github.com/potterhere/CS-note/tree/master/DesignPattern/StructureMode_Adapter
相关模式
桥接模式
装饰器模式
参考资料
1. 《设计模式:可复用面向对象软件的基础》 GOF