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
 */
相关推荐
geovindu6 小时前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
Kel10 小时前
Pregel 为什么会成为LangGraph编排的心脏
人工智能·设计模式·架构
会周易的程序员13 小时前
microLog 后端开发指南
开发语言·c++·物联网·设计模式·日志·iot·aiot
geovindu15 小时前
go: Functional Options Pattern
开发语言·后端·设计模式·golang·函数式选项模式’·惯用法模式
Kel1 天前
MCP 传输链路全链路拆解:从字节流到协议栈的四层架构之旅
人工智能·设计模式·架构
atunet1 天前
关于算法设计模式的演化与编程范式变迁的技术7
算法·设计模式
geovindu2 天前
go:Timing Functions Pattern
开发语言·后端·设计模式·golang·计时函数模式·性能分析模式
咖啡八杯3 天前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
槑有老呆3 天前
从 Prompt Engineering 到 Harness Engineering:AI 编程的下一次跃迁
设计模式
HjhIron4 天前
从Prompt到Context:大模型应用开发的范式转移
设计模式·aigc·ai编程