Java23种设计模式-结构型模式之适配器模式

适配器模式(Adapter Pattern):核心思想是将现有的接口 转换为客户端所期望的接口。它允许通过将一个接口转换为另一个接口,将不兼容的类或对象组合在一起。12

主要角色包括:
目标(Target)接口:当前系统业务所期待的接口,可以是抽象类或接口。
适配者(Adaptee)类:它是被访问和适配的现存组件库中的组件接口。
适配器(Adapter)类:它是一个转换器,通过继承或引用适配者的对象,把适配者接口转换成目标接口,让客户按目标接口的格式访问适配者。

优点:

1.客户端可以通过适配器透明地调用目标接口。

2.复用了现存的类,程序员不需要修改原有代码而重用现有的适配者类。

3.将目标类和适配者类解耦,解决了目标类和适配者类接口不一致的问题。

5.在很多业务场景中符合开闭原则。
缺点:

1.适配器编写过程需要结合业务场景全面考虑,可能会增加系统的复杂性。

2.可能增加代码阅读难度,降低代码可读性,过多使用适配器会使系统代码变得凌乱。

示例:创建一个MediaPlayer接口和一个实现了这个接口的AudioPlayer类,以及一个适配器类MediaAdapter,它将用于将不同格式的音频文件转换为MediaPlayer接口所需的格式

java 复制代码
//目标接口
public interface MediaPlayer {
    void play(String audioType,String fileName);

}
//适配器
public class MediaAdapter implements MediaPlayer{

    public MediaAdapter(String audioType) {
        System.out.println("MediaAdapter supports"+audioType+" adaption.");
    }

    @Override
    public void play(String audioType, String fileName) {
        System.out.println("Playing " + audioType + " file. Name: " + fileName);
    }
}
//适配者
public class AudioPlayer implements MediaPlayer{
    @Override
    public void play(String audioType, String fileName) {
        if (audioType.equalsIgnoreCase("mp3")){
            System.out.println("playing mp3 file. NameL:"+fileName);
        }else if (audioType.equalsIgnoreCase("mp4")){
            MediaPlayer mediaPlayer=new MediaAdapter(audioType);
            mediaPlayer.play(audioType,fileName);
        }else {
            System.out.println("Invalid media. " + audioType + " format not supported");
        }
    }
}
public class AdapterPatternDemo {
    public static void main(String[] args) {
        MediaPlayer mediaPlayer=new AudioPlayer();
        mediaPlayer.play("mp3", "beyond the horizon.mp3");
        mediaPlayer.play("mp4", "alone.mp4");
        mediaPlayer.play("mp3", "water like wine.mp3");
    }
}
/**
 * playing mp3 file. NameL:beyond the horizon.mp3
 * MediaAdapter supportsmp4 adaption.
 * Playing mp4 file. Name: alone.mp4
 * playing mp3 file. NameL:water like wine.mp3
 */
相关推荐
geovindu10 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
geovindu2 天前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
Mh6 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊7 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式
dahaihua3338 天前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
wy_hhxx8 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥8 天前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
用户624293196629 天前
告别 Electron 臃肿与 Wireshark 老化界面:用 Rust + Tauri 2.0 构建多总线网络与现场总线深度分析仪 Omni-Probe
设计模式
是2的10次方啊9 天前
设计模式与生活㉒:暖气热不热,得一间一间摸过去
设计模式
bigbread10 天前
迭代器模式-在区域健康档案导出中的实战应用
设计模式