适配器模式(Adapter Pattern)是指将一个类的接口转移成用户期望的另外一个接口,使原本接口不兼容的类可以一起工作,属于结构性设计模式。平常的充电器转换头就是一个适配器。
场景:
- 已存在的类的方法和需求不匹配的情况
下面就以充电器转换头为例
- android 充电器
public class MicroUSB {
public void chargingHead(){
System.out.println("android 充电接口");
}
}
- Type-C 转接头
public interface TypeC {
void typeCConverter();
}
- 苹果 转接头
public interface Iphone {
void iphoneConverter();
}
- 转接头适配器
public class ChargeAdapter implements TypeC,Iphone {
private MicroUSB microUSB;
public ChargeAdapter(MicroUSB microUSB) {
this.microUSB = microUSB;
}
@Override
public void typeCConverter() {
microUSB.chargingHead();
System.out.println("android接口变type-c 接口");
}
@Override
public void iphoneConverter() {
microUSB.chargingHead();
System.out.println("android接口变 iphone 接口");
}
}
- 运行
public class Run {
public static void main(String[] args) {
ChargeAdapter adapter = new ChargeAdapter(new MicroUSB());
adapter.typeCConverter();
adapter.iphoneConverter();
}
}
- 结果
android 充电接口
android 接口变type-c 接口
android 充电接口
android 接口变 iphone 接口
- 优点
- 提高类的透明性和复用性,原有的接口被复用,但不需要做修改
- 目标类和适配器类解耦,提高程序扩展性
- 符合开闭原则
- 缺点
- 可能会增加程序的复杂性
- 增加阅读难度,降低代码可读性
来源:CSDN
作者:Eternal1125
链接:https://blog.csdn.net/qq_36306590/article/details/104214237