设计模式之适配器模式

适配器模式

文章目录

定义

适配器模式(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. 定义接口

    java 复制代码
    public interface Target {
        void request();
    }
  2. 实现类

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

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

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

    java 复制代码
    @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

相关推荐
feiyu_gao1 小时前
Cocreation Framework:一套给所有人的 AI 协作思考系统
设计模式·aigc·ai编程
善良勤劳勇敢而又聪明的老杨1 天前
【AI编程系列】MCP 常用设计模式解读
设计模式·ai编程
geovindu1 天前
java: Strategy Pattern
java·开发语言·后端·设计模式·策略模式·行为模式
码匠许师傅2 天前
【设计模式精讲】29.行为型模式总结与对比(Behavioral Patterns Summary)
c++·设计模式·uml
geovindu2 天前
CSharp: Observer Pattern
开发语言·后端·观察者模式·设计模式·c#·.netcore·行为模式
yuehuaxin012 天前
LP8728A/LP8728B 芯茂微|SOP8L 副边反馈 PWM,18‑30W 适配器恒功率补偿方案解析
嵌入式硬件·智能家居·适配器模式·智能硬件
YHHLAI2 天前
NestJS 后端开发实战:从设计模式到 CRUD 全栈
设计模式
2401_868534783 天前
长远目标 Long-term Goal 老题沿用
设计模式·需求分析
吃饱了得干活3 天前
Java设计模式实战:一个支付模块的重构之旅,层层递进理解设计模式精髓
后端·设计模式·架构
vivo互联网技术3 天前
软件不是从数据开始,而是从现实开始 | KDC 系列 01
设计模式·架构·领域驱动设计