适配器模式是一种结构型设计模式,它允许将一个类的接口转换成客户端所期待的另一个接口。通常用于使原本由于接口不兼容而不能一起工作的类能够协同工作。
下列适配器模式演示基于经典的 “方钉和圆孔” 问题。
适配器假扮成一个圆钉 (RoundPeg), 其半径等于方钉 (SquarePeg) 横截面对角线的一半 (即能够容纳方钉的最小外接圆的半径)。
代码示例
圆孔:RoundHole
public class RoundHole {
private double radius;
public RoundHole(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public boolean fits(RoundPeg peg) {
boolean result;
result = (this.getRadius() >= peg.getRadius());
return result;
}
}
圆钉:RoundPeg
public class RoundPeg {
private double radius;
public RoundPeg() {}
public RoundPeg(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
}
方钉:SquarePeg
public class SquarePeg {
private double width;
public SquarePeg(double width) {
this.width = width;
}
public double getWidth() {
return width;
}
public double getSquare() {
double result;
result = Math.pow(this.width, 2);
return result;
}
}
方钉到圆孔的适配器:SquarePegAdapter
public class SquarePegAdapter extends RoundPeg {
private SquarePeg peg;
public SquarePegAdapter(SquarePeg peg) {
this.peg = peg;
}
@Override
public double getRadius() {
double result;
result = (Math.sqrt(Math.pow((peg.getWidth() / 2), 2) * 2));
return result;
}
}
运行示例:
public static void main(String[] args) {
RoundHole roundHole = new RoundHole(5);
RoundPeg roundPeg = new RoundPeg(5);
// 圆钉兼容圆孔
System.out.println(roundHole.fits(roundPeg));
SquarePeg squarePeg = new SquarePeg(2);
//方钉不兼容圆孔
// roundHole.fits(squarePeg);
// 通过适配器使方钉兼容圆孔
SquarePegAdapter sqPegAdapter = new SquarePegAdapter(squarePeg);
System.out.println(roundHole.fits(sqPegAdapter));
}
优点:
- 单一职责原则你可以将接口或数据转换代码从程序主要业务逻辑中分离。
- 符合开闭原则。 只要客户端代码通过客户端接口与适配器进行交互, 你就能在不修改现有客户端代码的情况下在程序中添加新类型的适配器。
缺点:
- 多使用会增加复杂性: 如果过度使用适配器模式,可能会增加系统的复杂性。
- 过多适配器类: 当需要适配多个类或接口时,可能需要创建多个适配器类。
适用场景:
- 接口不兼容:当你希望使用某个类, 但是其接口与其他代码不兼容时, 可以使用适配器类
- 旧系统升级:当需要复用旧系统中的类而这些类的接口与现有系统的接口不兼容时,可以使用适配器模式。