设计模式-适配器模式(Adapter)

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/love905661433/article/details/84398298

概述

  • 定义 : 将一个类的接口转换成客户期望的另一个接口

  • 使原本不兼容的类可以一起工作

  • 类型 : 结构型

适用场景

  • 已经存在的类, 它的方法和需求不匹配时(方法结果相同或相似)
  • 不是软件设计阶段考虑的设计模式, 而是随着软件维护, 由于不同产品, 不同厂家造成功能类似而接口不相同情况下的解决方案

优点

  • 能提高类的透明性和复用, 现有的类复用但不需要改变
  • 目标类和适配器类解耦, 提高程序扩展性
  • 符合开闭原则

缺点

  • 适配器编写过程需要全面考虑, 可能会增加系统的复杂性
  • 增加系统可读的难度

分类

  • 类适配器, 使用继承
  • 对象适配器, 使用组合

模式角色

  • Target : 定义C l i e n t使用的与特定领域相关的接口
  • Client : 客户端, 与符合Target 接口的对象协同
  • Adaptee : 定义一个已经存在的接口,这个接口需要适配
  • Adapter : 对A d a p t e e的接口与Target 接口进行适配

代码实现

类适配器

UML类图 :
在这里插入图片描述
Adaptee代码:

/**
 * 被适配的类
 *
 * @author 七夜雪
 * @create 2018-11-23 16:13
 */
public class Adaptee {
    public void AdapteeRequest(){
        System.out.println("被适配的类方法...");
    }
}

Target接口:

/**
 * @author 七夜雪
 * @create 2018-11-23 16:12
 */
public interface Target {
    public void request();
}

Target实现, 用于做对比, 代码如下:

/**
 * Target的一个实现类
 * @author 七夜雪
 * @create 2018-11-23 16:14
 */
public class TargetImpl implements Target {
    @Override
    public void request() {
        System.out.println("TargetImpl 方法...");
    }
}

适配器Adapter类 :

/**
 * 适配器类
 *
 * @author 七夜雪
 * @create 2018-11-23 16:15
 */
public class Adapter extends Adaptee implements Target {
    @Override
    public void request() {
        super.AdapteeRequest();
    }
}

测试代码:

    public static void main(String[] args) {
        Target target = new TargetImpl();
        target.request();
        target = new Adapter();
        target.request();
    }

测试结果:

TargetImpl 方法…
被适配的类方法…

对象适配器

UML类图:
在这里插入图片描述

代码除了Adapter类之外, 其他均与类适配器一样, Adapter代码如下:

/**
 * 适配器类
 *
 * @author 七夜雪
 * @create 2018-11-23 16:15
 */
public class Adapter implements Target {
    private Adaptee adaptee = new Adaptee();
    @Override
    public void request() {
     adaptee.AdapteeRequest();
    }
}
  • 类适配器和对象适配器的区别就是类适配器使用继承来实现, 而对象适配器则使用组合来实现

本文参考:
慕课网<java设计模式精讲 Debug 方式+内存分析>课程
四人帮<设计模式>

猜你喜欢

转载自blog.csdn.net/love905661433/article/details/84398298