1.简介
在我们的应用程序中我们可能需要将两个不同接口的类来进行通信,在不修改这两个的前提下我们可能会需要某个中间件来完成这个衔接的过程。这个中间件就是适配器。
所谓适配器模式就是将一个类的接口,转换成客户期望的另一个接口。它可以让原本两个不兼容的接口能够无缝完成对接。
适配器分为类适配器和对象适配器
2.类适配器代码
//目标接口
interface Target{
public void request();
}
//适配者接口
class Adaptee{
public void specificRequest(){
System.out.println("适配者中的业务代码被调用!");
}
}
//类适配器类
class ClassAdapter extends Adaptee implements Target{
public void request(){
specificRequest();
}
}
//客户端代码
public class ClassAdapterTest{
public static void main(String[] args){
System.out.println("类适配器模式测试:");
Target target = new ClassAdapter();
target.request();
}
}
执行结果如下:
类适配器模式测试:
适配者中的业务代码被调用!
3.对象适配器代码
//目标接口
interface Target{
public void request();
}
//适配者接口
class Adaptee{
public void specificRequest(){
System.out.println("适配者中的业务代码被调用!");
}
}
//对象适配器类
class ObjectAdapter implements Target{
private Adaptee adaptee;
public ObjectAdapter(Adaptee adaptee){
this.adaptee=adaptee;
}
public void request(){
adaptee.specificRequest();
}
}
//客户端代码
public class ObjectAdapterTest{
public static void main(String[] args){
System.out.println("对象适配器模式测试:");
Adaptee adaptee = new Adaptee();
Target target = new ObjectAdapter(adaptee);
target.request();
}
}
执行结果如下:
对象适配器模式测试:
适配者中的业务代码被调用!
4.使用场景
需要有一个接口,一个具体实现类,一个适配器
接口:这个接口最好是只有一个方法,避免适配器实现它时重写多个不必要的方法,如果实际项目中没有这样的接口,那我们就自己写一个
具体实现类:这是被调用方法的一方
5.参考
适配器模式(Adapter模式)详解
JAVA设计模式总结之23种设计模式
6.致谢
感谢自己记录下了适配器模式,面试要考!
网友评论