简介
适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。举个真实的例子,读卡器是作为内存卡和笔记本之间的适配器。您将内存卡插入读卡器,再将读卡器插入笔记本,这样就可以通过笔记本来读取内存卡。
类图
如何解决问题
- 定义一个单独的
adapter
类,将类(adaptee
)的(不兼容的)接口转换为target
客户端需要的另一个接口。 - 通过
adapter
完成adaptee
类的调用。
这种模式的关键思想是通过一个适配器类(adapter
)来适应一个已经存在的类而不用去改变他。
角色说明
- target:目标结构期望使用的接口
- adaptee:适配者,与目标接口不兼容(不能直接使用)
- adapter:适配器,将adaptee转换为target能够使用的形式
实现方案
类的适配器
Adapter与Adaptee是继承关系
public interface Target {
//这是能够使用的方法(期望的方法)
public void operation();
}
public class Adaptee {
//该方法target不能直接使用
public void specificOperation(){
}
}
/适配器Adapter继承Adaptee,同时实现了目标(Target)接口。
public class Adapter extends Adaptee implements Target {
@Override
public void operation() {
//做了一层封装
this.specificOperation();
}
}
对象的适配器
Adapter与Adaptee是委托关系
public interface Target {
//这是能够使用的方法(期望的方法)
public void operation();
}
public class Adaptee {
//该方法target不能直接使用
public void specificOperation(){
}
}
//关键点在这里,对象的适配器模式使用委托,而不是继承
public class Adapter implements Target {
// 直接关联被适配类
private Adaptee adaptee;
// 传入需要适配的对象
public Adapter (Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void operation() {
// 调用对象的方法,完成转换
this.adaptee.specificOperation();
}
}
参考地址
https://en.wikipedia.org/wiki/Adapter_pattern
https://blog.csdn.net/carson_ho/article/details/54910430
Q.E.D.
Comments | 0 条评论