设计模式之适配器模式

适配器模式

定义

适配器模式(Adapter Pattern)的定义如下:

Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.(将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。)
在这里插入图片描述

优缺点

优点
  1. 增加了类的透明性

    想想看,我们访问的Target目标角色,但是具体的实现都委托给了源角色,而这些对高层次模块是透明的,也是它不需要关心的

  2. 提高了类的复用度

    当然了,源角色在原有的系统中还是可以正常使用,而在目标角色中也可以充当新的演员。

  3. 灵活性非常好

    某一天,突然不想要适配器,没问题,删除掉这个适配器就可以了,其他的代码都不用修改,基本上就类似一个灵活的构件,想用就用,不想就卸载。

示例代码

  1. 定义接口

    public interface Target {
         
        void request();
    }
    
  2. 实现类

    public class ConcreteTarget implements Target {
         
        @Override
        public void request() {
         
            System.out.println("concrete receive request");
        }
    }
    
  3. 定义适配器

    public class Adaptee {
         
        public void doSomething() {
         
            System.out.println("do something");
        }
    }
    
  4. 具体类 继承适配器类以及实现Target接口

    public class Adapter extends Adaptee implements Target {
         
        @Override
        public void request() {
         
            super.doSomething();
        }
    }
    
  5. 测试方法

    @Test
    public void test() {
         
        // 原有的业务逻辑
        Target target = new ConcreteTarget();
        target.request();
        // 现在增加了适配器角色后的业务逻辑
        Target target2 = new Adapter();
        target2.request();
    }
    

    运行结果

    concrete receive request
    do something
    

源码地址

https://gitee.com/youxiaxiaomage/java-practices/tree/master/yxxmg-gof-sample/src/main/java/com/yxxmg/gof/structure/adapter

相关推荐

  1. 设计模式-适配器模式

    2024-01-01 08:38:06       37 阅读
  2. 设计模式适配器模式

    2024-01-01 08:38:06       19 阅读
  3. 设计模式适配器模式

    2024-01-01 08:38:06       16 阅读
  4. 设计模式适配器模式

    2024-01-01 08:38:06       10 阅读
  5. 设计模式适配器模式

    2024-01-01 08:38:06       8 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-01 08:38:06       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-01 08:38:06       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-01 08:38:06       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-01 08:38:06       20 阅读

热门阅读

  1. 离线语音识别 sherpa-ncnn 尝鲜体验

    2024-01-01 08:38:06       39 阅读
  2. [设计模式 Go实现] 创建型~单例模式

    2024-01-01 08:38:06       36 阅读
  3. Anaconda下调用ArcGIS的arcpy工具包

    2024-01-01 08:38:06       45 阅读
  4. 数据挖掘 模糊聚类

    2024-01-01 08:38:06       45 阅读
  5. LeetCode75| 单调栈

    2024-01-01 08:38:06       42 阅读
  6. 一篇文章认识微服务的优缺点和微服务技术栈

    2024-01-01 08:38:06       37 阅读