设计模式之适配器模式

适配器模式

文章目录

定义

适配器模式(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

相关推荐
fakerth2 分钟前
【OpenHarmony】设计模式模块详解
c++·单例模式·设计模式·openharmony
alibli3 小时前
一文学会设计模式之创建型模式及最佳实现
c++·设计模式
1024肥宅5 小时前
前端常用模式:提升代码质量的四大核心模式
前端·javascript·设计模式
郝学胜-神的一滴9 小时前
设计模式依赖于多态特性
java·开发语言·c++·python·程序人生·设计模式·软件工程
帅次9 小时前
系统分析师:软件需求工程的软件需求概述、需求获取、需求分析
设计模式·重构·软件工程·团队开发·软件构建·需求分析·规格说明书
EXtreme3510 小时前
【数据结构】算法艺术:如何用两个栈(LIFO)优雅地模拟队列(FIFO)?
c语言·数据结构·算法·设计模式·栈与队列·摊还分析·算法艺术
1024肥宅1 天前
JavaScript常用设计模式完整指南
前端·javascript·设计模式
特立独行的猫a1 天前
C++观察者模式设计及实现:玩转设计模式的发布-订阅机制
c++·观察者模式·设计模式
better_liang1 天前
每日Java面试场景题知识点之-单例模式
java·单例模式·设计模式·面试·企业级开发
sg_knight1 天前
什么是设计模式?为什么 Python 也需要设计模式
开发语言·python·设计模式