适配器模式
适配器模式(Adapter Pattern)将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。
适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。常用作在不修改源代码的情况下让已经存在的类能和其他类一起使用。
根据适配器类和适配者类的关系,适配器模式可以分为以下两种:
-
对象适配器模式(组合的方式)
- 类适配器模式(继承的方式)
为什么
试想一下,如果我们不使用适配器模式,我们可以选择修改源码或者更改我们的目标接口。而修改源码或是更改接口很大的代价很大,甚至是我们根本就没有源码。就好像我们无法更换插座接口或是充电器的接头一样。
怎么做
由于适配器模式有多种,下面通过几个代码片段来分别学习一下:
- 对象适配器模式
- 类适配器模式
定义目标接口
/**
* 目标接口
*
*/
public interface Target {
void request();
}
定义适配者类
/**
* 适配者类
*
*/
public class Adaptee {
/**
* 客户期望使用的业务方法
*/
public void specificRequest() {
System.out.println("Adaptee Specific request!");
}
}
定义对象适配器类
/**
* 适配器类(对象适配器模式实现)
*/
public class Adapter implements Target {
// 以组合的方式关联适配者
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void setAdaptee(Adaptee adaptee) {
this.adaptee = adaptee;
}
/**
* 对接口进行转换
*/
public void request() {
adaptee.specificRequest();
}
}
定义类适配器类
/**
* 类适配器模式
*
*/
public class AdapterClass extends Adaptee implements Target {
public void request() {
specificRequest();
}
}
创建请求
public class Main {
public static void main(String[] args) {
// 对象是配器模式
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.request();
// 类适配器模式
Target target1 = new AdapterClass();
target1.request();
}
}