阅读文章:https://refactoringguru.cn/design-patterns/adapter
一、解决了什么问题
适配器模式是一种结构型设计模式,它能使接口不兼容的对象能够相互合作
二、不使用此设计模式会出现什么情况
无法将不兼容的对象进行相互合作
三、符合什么原则
1、通过适配器做到可插拔,同时不影响现有的结构保持开闭原则
**开闭原则:**对扩展开放,对修改关闭
2、单一职责原则:可以将接口或数据转换代码从程序主要业务逻辑中分离
**单一职责原则:**一个类只负责一项职责
四、代码实现
例子:让方钉适配圆孔
圆钉:
public class RoundPeg {
private double radius;
public RoundPeg() {}
public RoundPeg(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
}
方钉:
public class SquarePeg {
private double width;
public SquarePeg(double width) {
this.width = width;
}
public double getWidth() {
return width;
}
}
圆孔:
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.radius >= peg.getRadius());
return result;
}
}
方钉适配器:
public class SquarePegAdapter extends RoundPeg{
private SquarePeg squarePeg;
public SquarePegAdapter(SquarePeg squarePeg) {
this.squarePeg = squarePeg;
}
//重写圆钉获取的数据的方法
@Override
public double getRadius() {
double result;
result = Math.sqrt(Math.pow((squarePeg.getWidth() / 2),2) * 2);
return result;
}
}
测试:
public class AdapterTest {
public static void main(String[] args) {
RoundHole hole = new RoundHole(5);
RoundPeg roundPeg = new RoundPeg(5);
if (hole.fits(roundPeg)) {
System.out.println("圆孔圆钉配对成功");
}
SquarePeg smallPeg = new SquarePeg(2);
SquarePeg largePeg = new SquarePeg(20);
SquarePegAdapter smallPegAdapter = new SquarePegAdapter(smallPeg);
SquarePegAdapter largePegAdapter = new SquarePegAdapter(largePeg);
if (hole.fits(smallPegAdapter)) {
System.out.println("圆孔方钉配对成功");
}
if (!hole.fits(largePegAdapter)) {
System.out.println("圆孔方钉配对失败");
}
}
}
"圆孔方钉配对成功");
}
if (!hole.fits(largePegAdapter)) {
System.out.println("圆孔方钉配对失败");
}
}
}