适配器模式将某个类的接口转换成客户端期望的另一个接口表示, 主的目的是兼容性, 让原本因接口不匹配不能一起工作的两个类可以协同工作. 其别名为包装器 (Wrapper).
简单地说, 就是需要的东西就在面前, 但却不能使用, 而短时间又无法改造它, 于是我们就想办法适配它.
适配器分类:
类适配器模式
对象的适配器模式
接口的适配器模式
注: 如果对类图中的箭头有疑惑参考: UML 类图中的六种关系 (物理设计阶段)
1. 类适配器模式
在 Adapter 中实现目标接口同时继承待适配类来完成适配:
Target 为目标接口类
Adaptee 为待适配类
Adapter 适配器类: 将 Adaptee 适配为 Target 接口
- // 已存在的, 具有特殊功能, 但不符合我们既有的标准接口的类
- class Adaptee {
- public void specificRequest() {
- System.out.println("被适配的类, 该类具有特殊功能");
- }
- }
- // 目标接口
- interface Target {
- public void request();
- }
- // 具体目标类, 只提供普通功能
- class ConcreteTarget implements Target {
- public void request() {
- System.out.println("普通类, 该类具有普通功能");
- }
- }
- // 适配器类, 继承了被适配类, 同时实现标准接口
- class Adapter extends Adaptee implements Target{
- public void request() {
- super.specificRequest();
- }
- }
- // 测试类
- // 使用普通功能类
- Target concreteTarget = new ConcreteTarget();
- concreteTarget.request(); // 输出 "普通类, 该类具有普通功能"
- // 使用特殊功能类, 即适配类
- Target adapter = new Adapter();
- adapter.request(); // 输出 "被适配的类, 该类具有特殊功能"
2. 对象的适配器模式
与类适配器不同的是, 对象适配器持有 Adaptee 对象而不需要继承它.
- // 只需要修改适配器类即可
- // 适配器类, 只实现标准接口
- class Adapter implements Target{
- private Adaptee adaptee;
- public Adapter (Adaptee adaptee) {
- this.adaptee = adaptee;
- }
- public void request() {
- this.adaptee.specificRequest();
- }
- }
- // 测试类
- Target concreteTarget = new ConcreteTarget();
- concreteTarget.request(); // 输出 "普通类, 该类具有普通功能"
- //Adapter 需要先创建一个被适配类的对象作为参数
- Target adapter = new Adapter(new Adaptee());
- adapter.request(); // 输出 "被适配的类, 该类具有特殊功能"
- ---------------------
作者: SEU_Calvin
来源: https://www.cnblogs.com/NeilZhang/p/10279549.html