适配器模式
...大约 2 分钟
适配器是一种结构型设计模式, 它能使不兼容的对象能够相互合作。
适配器可担任两个对象间的封装器, 它会接收对于一个对象的调用, 并将其转换为另一个对象可识别的格式和接口。
使用示例: 适配器模式在 Java 代码中很常见。 基于一些遗留代码的系统常常会使用该模式。 在这种情况下, 适配器让遗留代码与现代的类得以相互合作。
Java 核心程序库中有一些标准的适配器:
java.util.Arrays#asList()
java.util.Collections#list()
java.util.Collections#enumeration()
java.io.InputStreamReader(InputStream)
(返回Reader
对象)java.io.OutputStreamWriter(OutputStream)
(返回Writer
对象)javax.xml.bind.annotation.adapters.XmlAdapter#marshal()
和#unmarshal()
识别方法: 适配器可以通过以不同抽象或接口类型实例为参数的构造函数来识别。 当适配器的任何方法被调用时, 它会将参数转换为合适的格式, 然后将调用定向到其封装对象中的一个或多个方法。
让方钉适配圆孔
这个简单的例子展示了适配器如何让不兼容的对象相互合作。
项目结构

round
round/RoundHole.java: 圆孔
public class RoundHole {
// 定义一个成员变量
private final double radius;
// 构造函数
public RoundHole(double radius) {
this.radius = radius;
}
// 定义一个方法,用于判断某个圆孔是否能够放入某个圆钉
public boolean fits(RoundPeg roundPeg) {
return radius >= roundPeg.getRadius();
}
}
round/RoundPeg.java: 圆钉
public class RoundPeg {
private double radius;
public RoundPeg() {}
public RoundPeg(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
}
square
square/SquarePeg.java**😗* 方钉
public class SquarePeg {
private final double width;
public double getWidth() {
return width;
}
public SquarePeg(double width) {
this.width = width;
}
}
adapters
adapters/SquarePegAdapter.java: 方钉到圆孔的适配器
// 适配器允许将方形钉子安装到圆孔中,适配谁就继承谁
public class SquarePegAdapter extends RoundPeg {
private final 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;
}
}
Demo
public class Main {
public static void main(String[] args) {
RoundPeg roundPeg = new RoundPeg(5);
RoundHole roundHole = new RoundHole(5);
if (roundHole.fits(roundPeg)){
System.out.println("圆钉 r5 适合圆孔 r5");
}else{
System.out.println("圆钉 r5 不适合圆孔 r5");
}
SquarePeg squarePeg = new SquarePeg(6);
// 适配器
SquarePegAdapter squarePegAdapter = new SquarePegAdapter(squarePeg);
System.out.println("正方形钉半径:"+squarePegAdapter.getRadius());
if (roundHole.fits(squarePegAdapter)){
System.out.println("正方形钉 r6 适合圆孔 r5");
}else {
System.out.println("正方形钉 r6 不适合圆孔 r5");
}
}
}
结果: