1、适配器模式的学习
  当我们需要将一个类的接口转换成另一个客户端所期望的接口时,适配器模式(Adapter Pattern)可以派上用场。它允许不兼容的接口之间能够协同工作。
   适配器模式属于结构型设计模式,它包含以下几个角色:
- 目标接口(Target Interface):客户端所期望的接口,也是适配器类要实现的接口。
- 适配器(Adapter):适配器类将被适配者的接口转换成目标接口。它实现了目标接口,并包含一个对被适配者的引用。
- 被适配者(Adaptee):被适配者是我们需要将其接口转换的类。它拥有客户端所不兼容的接口。
 适配器模式的核心思想是通过适配器类来包装被适配者,使其能够与目标接口协同工作。适配器在自身的实现中调用被适配者的方法,将其转换成客户端所期望的接口形式。
 适配器模式可以有两种实现方式:
 类适配器模式:适配器类继承被适配者类,并实现目标接口。通过继承,适配器类同时具有目标接口和被适配者的特性。
 对象适配器模式:适配器类持有被适配者对象的引用,并实现目标接口。通过对象组合,适配器类可以调用被适配者对象的方法来实现目标接口。
  
2、适配器模式的使用
  因为类适配器模式涉及到了继承,相对于对象适配器模式耦合度增加了;所以推荐使用对象适配器模式,代码示例以对象适配器模式为例。
   假设你正在开发一个多媒体播放器应用程序,它可以播放不同格式的音频文件,如MP3、WAV和FLAC。现在你需要添加对新的音频格式OGG的支持,但是你的播放器类只能接受实现了MediaPlayer接口的类。你需要使用适配器模式来将OGGPlayer适配成符合MediaPlayer接口的类。
   MediaPlayer接口
/**
 * @author myf
 * 播放器
 */
public interface MediaPlayer {
    /**
     * 播放
     */
    void play();
}
OGGPlayer接口及实现类
/**
 * @author myf
 * OGGPlayer 接口
 */
public interface OGGPlayer {
    /**
     * OGG格式媒体播放
     */
    void play();
}
/**
 * @Author: myf
 * @CreateTime: 2023-06-02  21:19
 * @Description: OGGPlayerImpl OGG格式播放类
 */
public class OGGPlayerImpl implements OGGPlayer{
    @Override
    public void play() {
        System.out.println("OGG格式媒体开始播放");
    }
}
适配器
/**
 * @Author: myf
 * @CreateTime: 2023-06-02  21:33
 * @Description: OGGPlayerAdapter   OGG格式媒体适配器类
 */
public class OGGPlayerToMediaPlayerAdapter implements MediaPlayer {
    private OGGPlayer oggPlayer;
    public OGGPlayerToMediaPlayerAdapter(OGGPlayer oggPlayer) {
        this.oggPlayer = oggPlayer;
    }
    @Override
    public void play() {
        oggPlayer.play();
    }
}
客户端
public class MediaClient {
    
    public static void main(String[] args) {
        //播放OGG格式媒体
        play(new OGGPlayerToMediaPlayerAdapter(new OGGPlayerImpl()));
    }
    private static void play(MediaPlayer mediaPlayer) {
        mediaPlayer.play();
    }
}
OGG格式媒体开始播放
















