Adapter 设计模式

本篇对应《图解设计模式》第二章。

适配器模式就是“把一个接口转换成另外一个接口”。


Samsung SD Adapter for microSD

比如我们要实现一个 TF (microSD) 卡转 SD 卡适配器。

定义 SdCard 接口。

public interface SdCard {
    /**
     * read data from SD card
     * @return
     */
    public String readSd();

    /**
     * write data to SD card
     * @param data
     * @return
     */
    public Boolean writeSd(String data);
}

定义 TfCard 接口。

public interface TfCard {
    /**
     * read data from TF card
     * @return
     */
    public String readTf();

    /**
     * write data to TF card
     * @param data
     * @return
     */
    public Boolean writeTf(String data);
}

实现 SdCardAdapter。

public class SdCardAdapter implements SdCard {
    /**
     * TF card
     */
    private TfCard tfCard;

    /**
     * read data from TF card (using SD card adpater)
     */
    @Override
    public String readSd() {
        return tfCard.readTf();
    }

    /**
     * write data to TF card (using SD card adpater)
     */
    @Override
    public Boolean writeSd(String data) {
        return tfCard.writeTf(data);
    }
}

参考:

https://book.douban.com/subject/26933281/

https://www.runoob.com/design-pattern/adapter-pattern.html

81 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *