适配器模式

适配器模式

文章目录

什么是适配器模式

适配器模式(Adapter),将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一

起工作的那些类可以一起工作。

  • Target:这是客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口
  • Adapter:通过在内部包装一个Adaptee对象,把源接口转换成目标接口
  • Adeptee:需要适配的类

示例

适配器模式是一种结构型设计模式,它允许将一个接口转换成客户希望的另一个接口,使原本因接口不兼容而不能一起工作的类能够协同工作。适配器模式包含以下角色:

  • Target(目标接口):客户期待的接口
  • Adaptee(被适配者):现有的、需要被适配的接口
  • Adapter(适配器):实现目标接口,并持有被适配者的实例,负责将被适配者的方法转换为目标接口的方法

下面是一个使用 Java 实现适配器模式的示例,假设有一个音频播放器(AudioPlayer)需要播放不同格式的音乐文件,但只能直接播放 MP3 文件。为了使其能够播放 WAV 和 OGG 格式的文件,我们需要创建适配器来将这两种格式转换为 MP3 格式。

1.首先,定义音频播放器期待的目标接口(Target):

java 复制代码
public interface AudioPlayer {
    void play(String fileName, String fileType);
}

2.接着,定义现有音频文件接口(Adaptees):

java 复制代码
public class MP3File {
    public void play() {
        System.out.println("Playing MP3 file...");
    }
}
java 复制代码
public class WAVFile {
    public void decodeAndPlay() {
        System.out.println("Decoding and playing WAV file...");
    }
}
java 复制代码
public class OGGFile {
    public void convertAndPlay() {
        System.out.println("Converting and playing OGG file...");
    }
}

3.然后,创建适配器类(Adapter),实现目标接口(AudioPlayer),并持有被适配者(WAVFile 和 OGGFile)的实例:

java 复制代码
public class WAVAdapter implements AudioPlayer {
    private WAVFile wavFile;

    public WAVAdapter(WAVFile wavFile) {
        this.wavFile = wavFile;
    }

    @Override
    public void play(String fileName, String fileType) {
        if ("wav".equals(fileType)) {
            wavFile.decodeAndPlay();
        } else {
            System.out.println("Unsupported file type for WAVAdapter.");
        }
    }
}
java 复制代码
public class OGGAdapter implements AudioPlayer {
    private OGGFile oggFile;

    public OGGAdapter(OGGFile oggFile) {
        this.oggFile = oggFile;
    }

    @Override
    public void play(String fileName, String fileType) {
        if ("ogg".equals(fileType)) {
            oggFile.convertAndPlay();
        } else {
            System.out.println("Unsupported file type for OGGAdapter.");
        }
    }
}

4.最后,创建音频播放器(AudioPlayer)并使用适配器播放不同格式的文件:

java 复制代码
public class Main {
    public static void main(String[] args) {
        AudioPlayer audioPlayer = new AudioPlayer() {
            @Override
            public void play(String fileName, String fileType) {
                if ("mp3".equals(fileType)) {
                    new MP3File().play();
                } else if ("wav".equals(fileType)) {
                    new WAVAdapter(new WAVFile()).play(fileName, fileType);
                } else if ("ogg".equals(fileType)) {
                    new OGGAdapter(new OGGFile()).play(fileName, fileType);
                } else {
                    System.out.println("Unsupported file type.");
                }
            }
        };

        audioPlayer.play("song1.mp3", "mp3");
        audioPlayer.play("song2.wav", "wav");
        audioPlayer.play("song3.ogg", "ogg");
    }
}

在这个示例中,AudioPlayer 是目标接口,MP3File、WAVFile 和 OGGFile 是被适配者,WAVAdapter 和 OGGAdapter 是适配器。通过适配器,原本只能播放 MP3 文件的音频播放器现在也能播放 WAV 和 OGG 格式的文件,实现了不同接口之间的无缝对接。这就是适配器模式的应用。

相关推荐
孟健9 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞11 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽13 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程18 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪18 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook18 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python