适配器模式
适配器模式的使用场景:我们在应用程序中已经设计好了功能接口,但是与第三方提供的接口类不一致。第三方的接口类已经不能更改,我们设计的功能接口也是符合需求也不能改,为了使得这些接口不兼容的类(即不能在一起工作)可以一起工作,就可以使用适配器模式。
Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. -- GoF
适配器模式有两种类型:类适配器模式 和 对象适配器模式。
适配器模式参与者:
Client:与Target协同交互的类;
Target:Client所使用的相关接口或(抽象)类
Adaptee: 需要适配的类
Adapter: 适配器类,负责Adaptee中的接口方法与Target中的接口方法进行适配
1、类适配器模式:
代码如下:
//Target,此处为接口
public interface Target {
void request();
}
//Adaptee类
public class Adaptee {
public void specificRequest() {
System.out.println("adaptee 处理请求");
}
}
//Adapter类
public class Adapter extends Adaptee implements Target{
@Override
public void request() {
this.specificRequest();
}
}
//测试类
public class Test {
public static void main(String[] args) {
Target target = new Adapter();
target.request();
}
}
类适配器模式是通过类的继承实现的,缺点Adapter和Adaptee是耦合度高,而且一些高级语言像Java、C#不支持多继承,如果Target为(抽象)类,则只能使用对象适配器模式。
2、对象适配器模式
对象适配器模式是通过Adapter类聚合持有Adaptee类对象adaptee实现的,代码如下:
//Target,此处为接口
public interface Target {
void request();
}
//Adaptee类
public class Adaptee {
public void specificRequest() {
System.out.println("adaptee 处理请求");
}
}
//Adapter类
public class Adapter extends Adaptee implements Target{
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
}
//测试类
public class Test {
public static void main(String[] args) {
Target target = new Adapter(new Adaptee());
target.request();
}
}
小结:
适配器模式通常在软件开发后期或者维护期使用。在设计阶段如果出现接口方法不匹配,应该统一接口方法,而不是使用适配器模式。适配器模式更常见地用于我们适配第三方开发组件类提供的接口上。