设计模式之适配器模式

写在前面

适配器设计模式属于结构型设计模式的一种,本文一起来看下。

1:介绍

1.1:什么时候适配器设计模式

当现有接口客户端无法直接调用时,我们可以考虑适配器设计模式,来定义一个能够供客户端直接调用的接口,并在其中进行自动的适配(这也是适配器设计模式的核心)

1.2:UML类图

原型设计模式,包含如下元素:

1:Adaptee
    现有接口,该接口无法直接满足客户端需求。
2:Target
    适配接口,客户端可以直接调用
3:Adapter
    实现适配接口Target,提供适配,并最终调用Adaptee
4:Client
    客户端类,即使用者

具体分为类适配模式和对象适配模式,其中类适配模式是适配器类同样实现目标接口,从而直接调用,对象适配模式是通过组合现有接口的方式,对象适配模式UML图如下:

对象适配模式UML图如下(区别就是不再实现Target接口而是组合)

2:实例

源码

2.1:场景

现在有一个接口有一个方法需要一个List<String>的参数,但是客户端只能提供逗号分割的字符串作为参数,这样就可以定义一个接受逗号分割的字符串参数的接口,并提供实现进行适配。

2.2:程序

  • 现有接口和实现类
java 复制代码
// 现有接口
public interface Adaptee {
    void tellMeYourDream(List<String> list);
}

// 现有接口实现类
public class AdapteeImpl implements Adaptee {
    public void tellMeYourDream(List<String> list) {
        System.out.println("你的梦想列表:" + list);
    }
}
  • 适配接口
java 复制代码
// 客户端需要的接口
public interface Target {
    // 以逗号分割的字符串
    void tellMeYourDream(String content);
}
  • 类适配模式
java 复制代码
// 客户需要的接口实现类,即适配器类(注意这里extends AdapteeImpl就是类适配模式的来源)
public class TargetClassAdapter extends AdapteeImpl implements Target {
    public void tellMeYourDream(String content) {
        // 客户给的是逗号分割的字符串,这里适配成现有接口需要的List
        List<String> listResult = Splitter.on(",").splitToList(content);
        // 适配完成,调用现有类的方法
        super.tellMeYourDream(listResult);
    }
}

测试:

java 复制代码
@Test
public void classadapter() {
    Target target = new TargetClassAdapter();
    target.tellMeYourDream("世界和平,见到想见的人,平平淡淡");
}

你的梦想列表:[世界和平, 见到想见的人, 平平淡淡]
  • 对象适配模式
java 复制代码
// 客户需要的接口实现类,即适配器类
public class TargetObjectAdapter implements Target {
    private Adaptee adaptee;

    public TargetObjectAdapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    public void tellMeYourDream(String content) {
        // 客户给的是逗号分割的字符串,这里适配成现有接口需要的List
        List<String> listResult = Splitter.on(",").splitToList(content);
        // 适配完成,调用现有类的方法
//        super.tellMeYourDream(listResult);
        this.adaptee.tellMeYourDream(listResult);
    }
}

测试:

java 复制代码
@Test
public void objectadapter() {
    Target target = new TargetObjectAdapter(new AdapteeImpl());
    target.tellMeYourDream("世界和平,见到想见的人,平平淡淡");
}

你的梦想列表:[世界和平, 见到想见的人, 平平淡淡]

写在后面

参考文章列表

一文彻底弄懂适配器模式(Adapter Pattern)

相关推荐
ok!ko1 小时前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式
拉里小猪的迷弟2 小时前
设计模式-创建型-常用:单例模式、工厂模式、建造者模式
单例模式·设计模式·建造者模式·工厂模式
严文文-Chris4 小时前
【设计模式-中介者模式】
设计模式·中介者模式
刷帅耍帅4 小时前
设计模式-中介者模式
设计模式·中介者模式
刷帅耍帅5 小时前
设计模式-组合模式
设计模式·组合模式
刷帅耍帅6 小时前
设计模式-命令模式
设计模式·命令模式
码龄3年 审核中6 小时前
设计模式、系统设计 record part03
设计模式
刷帅耍帅6 小时前
设计模式-外观模式
设计模式·外观模式
刷帅耍帅7 小时前
设计模式-迭代器模式
设计模式·迭代器模式
liu_chunhai7 小时前
设计模式(3)builder
java·开发语言·设计模式