适配器模式
文章目录
什么是适配器模式
- Target:这是客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口
- Adapter:通过在内部包装一个Adaptee对象,把源接口转换成目标接口
- Adeptee:需要适配的类
示例
适配器模式是一种结构型设计模式,它允许将一个接口转换成客户希望的另一个接口,使原本因接口不兼容而不能一起工作的类能够协同工作。适配器模式包含以下角色:
- Target(目标接口):客户期待的接口
- Adaptee(被适配者):现有的、需要被适配的接口
- Adapter(适配器):实现目标接口,并持有被适配者的实例,负责将被适配者的方法转换为目标接口的方法
下面是一个使用 Java 实现适配器模式的示例,假设有一个音频播放器(AudioPlayer)需要播放不同格式的音乐文件,但只能直接播放 MP3 文件。为了使其能够播放 WAV 和 OGG 格式的文件,我们需要创建适配器来将这两种格式转换为 MP3 格式。
1.首先,定义音频播放器期待的目标接口(Target):
public interface AudioPlayer {
    void play(String fileName, String fileType);
}
2.接着,定义现有音频文件接口(Adaptees):
public class MP3File {
    public void play() {
        System.out.println("Playing MP3 file...");
    }
}
public class WAVFile {
    public void decodeAndPlay() {
        System.out.println("Decoding and playing WAV file...");
    }
}
public class OGGFile {
    public void convertAndPlay() {
        System.out.println("Converting and playing OGG file...");
    }
}
3.然后,创建适配器类(Adapter),实现目标接口(AudioPlayer),并持有被适配者(WAVFile 和 OGGFile)的实例:
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.");
        }
    }
}
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)并使用适配器播放不同格式的文件:
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");
    }
}










