适配器模式(Adapter Pattern):结构型模式的一种,把一个类的接口变成客户端所期待的另一种接口,从而使原本接口不匹配而无法一起工作的两个类能够在一起工作。
类适配器、对象适配器、接口适配器
? 1) 类适配器:使用组合
? 2) 对象适配器
? 3) 接口适配器
接口适配器的使用场景: 原有接口有很多方法,而我们只需要其中一部分,这是看可以用抽象类来实现该接口,不需要的方法只需要写个空方法(默认实现)就好了,接口目标类去实现自己需要的接口
适用的场景是不想实现原有类的所有方法
1) 类适配器
首先定义一个MicroCharger 类,表示Micro USB 的充电器,提供电源
/**
* 提供电源的 Micro 接口的充电器
*/
public class MicroCharger{
public void connection(){
System.out.println("使用 Mirco USB 充电");
}
}
定义华为手机客户端使用的接口,业务相关
/**
* 定义华为手机使用的接口 -> Type-c
*/
public interface Target {
void connection();
}
class TypeCDataLine implements Target {
@Override
public void connection() {
System.out.println("使用Type-c充电器为手机充电");
}
}
创建适配器类,继承被适配类,同时实现接口。
/**
* 创建类适配器,继承了被适配类,同时实现标准接口
*/
public class TypeCDataLineAdapter extends MicroCharger implements Target {
@Override
public void connection() {
System.out.println("Micro to type-c 转接头");
super.connection();
}
}
测试代码
public static void main(String[] args) {
Target target = new TypeCDataLine();
target.connection();
TypeCDataLineAdapter typeCDataLineAdapter = new TypeCDataLineAdapter();
typeCDataLineAdapter.connection();
}
结果如下:
![]()
2) 对象适配器
/**
* 创建适配器类,实现标准接口,将这个调用委托给实现新接口的对象来处理
*/
public class TypeCDataLineAdapter implements Target {
private Target target;
public TypeCDataLineAdapter(Target target) {
this.target = target;
}
@Override
public void connection() {
System.out.println("Micro to type-c 转接头");
target.connection();
}
}
测试
public static void main(String[] args) {
// 使用特殊功能类,即适配类
TypeCDataLineAdapter typeCDataLineAdapter = new TypeCDataLineAdapter( new TypeCDataLine() );
typeCDataLineAdapter.connection();
}
3) 区别:
优点
缺点
适用场景
原文:https://www.cnblogs.com/zhaoqiang-lab/p/13200907.html