概念
通过创建一个适配器类,将一个接口转换成客户端所期望的另一个接口
应用场景
适配器模式的目的是为了应对不同类或系统间接口不兼容的问题
基本结构

1)目标接口(Target):客户端希望使用的接口
2)适配器类(Adapter):实现了目标接口,并且通过委托的方式将请求转换为适配的接口调用
3)适配者类(Adaptee):已有的、需要适配的类
4)客户端(Client):通过目标接口与系统交互的代码
代码实现
以“绘制图形”为例
目标接口
最终客户端通过该接口使用
public interface Shape {
void draw(int x, int y, int width, int height);
}
适配者
需要将适配者的接口再包一层,套上目标接口的外壳
public class LegacyRectangle {
public void display(int x1, int y1, int x2, int y2) {
System.out.println("LegacyRectangle: Point1(" + x1 + ", " + y1 + "), Point2(" + x2 + ", " + y2 + ")");
}
}
适配器
通过继承目标接口,为适配者包上一层目标接口的外壳
public class RectangleAdapter implements Shape {
private LegacyRectangle legacyRectangle;
public RectangleAdapter(LegacyRectangle legacyRectangle) {
this.legacyRectangle = legacyRectangle;
}
@Override
public void draw(int x, int y, int width, int height) {
int x1 = x;
int y1 = y;
int x2 = x + width;
int y2 = y + height;
legacyRectangle.display(x1, y1, x2, y2);
}
}
客户端
以目标接口作为类型创建对象,客户端只需要通过该对象使用目标接口就行
public class AdapterPatternExample {
public static void main(String[] args) {
LegacyRectangle legacyRectangle = new LegacyRectangle();
Shape shapeAdapter = new RectangleAdapter(legacyRectangle);
shapeAdapter.draw(10, 20, 50, 30);
}
}
优缺点
优点
1)解耦系统:将不兼容的接口适配为客户端所需的接口,能够有效地解耦系统中的不同模块
2)简化接口:适配器模式可以将复杂的接口转换为简单的接口
缺点
1)过度使用:掩盖了系统设计的问题,造成长期维护上的困难
