摘要:/** * 模擬已經舊的接口 模擬該庫是個 jar 包,不能改它源碼 的情況下,適配器模式 實現我們的接口 * @author aodeng-低調小熊貓 * @since 19-7-17 */ public class ExistPlayer { /** *

* 播放mp3文件 *

* @author aodeng * @since 19-7-17 */ public void playMp3(String fileName){ System.out.println("play mp3"+fileName)。/** * 寫個適配器 適配器實現我們的新接口,在適配器中使用我們的舊接口 * @author aodeng-低調小熊貓 * @since 19-7-17 */ public class PlayerAdapter implements MusicPlayer{ //使用舊接口 private ExistPlayer existPlayer。

適配器模式

適配器模式將一個類的接口,轉換成客戶期望的另一個接口。適配器讓原本接口不兼容的類可以合作無間。

生活例子:充電頭和插座不兼容,而解決方法是買一個轉換頭,這是典型的適配器模式,轉換頭就是我們所說的適配器

適配器主要分爲兩種:類適配器(繼承),對象適配器(實現接口,使用較多)

使用場景:適配器適合用於解決新舊系統( 或新舊接口 )之間的兼容問題,而不建議在一開始就直接使用。

使用

舉例最近接了個音樂播放器的項目,要求支持 mp3、wma 等格式,於是定義了新接口:

/**
 * 模擬自己定義的新接口
 * @author aodeng-低調小熊貓
 * @since 19-7-17
 */
public interface MusicPlayer {

    /** 
    * <p>
    * 音樂播放器
    * </p> 
    * @author aodeng
    * @since 19-7-17
    */
    public void play(String type,String fileName);
}

但是想那麼多種格式要支持,自己去一一實現太麻煩了,乾脆直接找現成的庫來用用。

/**
 * 模擬已經舊的接口 模擬該庫是個 jar 包,不能改它源碼 的情況下,適配器模式 實現我們的接口
 * @author aodeng-低調小熊貓
 * @since 19-7-17
 */
public class ExistPlayer {

    /**
    * <p>
    * 播放mp3文件
    * </p>
    * @author aodeng
    * @since 19-7-17
    */
    public void playMp3(String fileName){
        System.out.println("play mp3"+fileName);
    }

    /**
    * <p>
    * 播放mp4文件
    * </p>
    * @author aodeng
    * @since 19-7-17
    */
    public void playMp4(String fileName){
        System.out.println("play mp4"+fileName);
    }
}

然後發現這個庫的接口跟自己定義的不一樣,而且該庫是個 jar 包,不能改它源碼,就算能改也不能這麼做,因爲其他地方可能有調用此處代碼,改了有可能會導致系統崩潰。

咋辦?寫個適配器唄。

/**
 * 寫個適配器 適配器實現我們的新接口,在適配器中使用我們的舊接口
 * @author aodeng-低調小熊貓
 * @since 19-7-17
 */
public class PlayerAdapter implements MusicPlayer{

    //使用舊接口
    private ExistPlayer existPlayer;

    public PlayerAdapter(){
        existPlayer=new ExistPlayer();
    }

    @Override
    public void play(String type, String fileName) {
        if ("mp3".equals(type)){
            existPlayer.playMp3(fileName);
        }else if ("mp4".equals(type)){
            existPlayer.playMp4(fileName);
        }

    }
}

測試結果

public static void main(String[] args) {
        System.out.println("Hello World!");
        //客戶端調用
        MusicPlayer musicPlayer=new PlayerAdapter();
        musicPlayer.play("mp3","XXX.mp3 file");
        musicPlayer.play("mp4","XXX.mp4 file");
        //控制檯輸出
        /*
        Hello World!
        play mp3XXX.mp3 file
        play mp4XXX.mp4 file
        */
    }

慢慢領悟其精髓

源碼

源碼地址: https://github.com/java-aodeng/hope

.ad:

人工智能被認爲是一種拯救世界、終結世界的技術。毋庸置疑,人工智能時代就要來臨了,科幻電影中的場景將成爲現實,未來已來! 詳情:

相關文章