適配器模式

Convert the interface of a class into another interface that clients expect. The adapter pattern lets classes work together that couldn’t otherwise because of incompatible interfaces.

鴨子接口及實(shí)現(xiàn)

/**
 * 鴨子
 */
public interface IDuck {
    void quack();

    void fly();
}
public class MallardDuck implements IDuck {
    @Override
    public void quack() {
        System.out.println("Quack...");
    }

    @Override
    public void fly() {
        System.out.println("Fly...");
    }
}

火雞接口及實(shí)現(xiàn)

/**
 * 火雞
 */
public interface ITurkey {
    void gobble();

    void fly();
}
public class WildTurkey implements ITurkey {
    @Override
    public void gobble() {
        System.out.println("Gobble...");
    }

    @Override
    public void fly() {
        System.out.println("Short fly...");
    }
}

適配器

火雞不能直接當(dāng)作鴨子來(lái)用,需要添加適配器,將火雞可以被當(dāng)做鴨子來(lái)用。

/**
 * 現(xiàn)在缺少 Duck ,需要使用 Turkey 來(lái)代替Duck。
 * 將Turkey適配為Duck,需要實(shí)現(xiàn)Duck接口(is a duck),并集成Turkey(has a turkey)
 */
public class TurkeyAdapter implements IDuck {
    ITurkey turkey;

    public TurkeyAdapter(ITurkey turkey) {
        this.turkey = turkey;
    }

    @Override
    public void quack() {
        turkey.gobble();
    }

    @Override
    public void fly() {
        // Turkey要飛五次才抵上Duck飛一次
        for (int i = 0; i < 5; i++) {
            turkey.fly();
        }
    }
}

執(zhí)行

public class Test {
    public static void main(String[] args) {
        IDuck mallardDuck = new MallardDuck();
        ITurkey wildTurkey = new WildTurkey();
        IDuck turkeyAdapter = new TurkeyAdapter(wildTurkey);

        System.out.println("Turkey:");
        wildTurkey.gobble();
        wildTurkey.fly();

        System.out.println("Duck:");
        testDuck(mallardDuck);

        System.out.println("TurkeyAdapter:");
        testDuck(turkeyAdapter);
    }

    static void testDuck(IDuck duck) {
        duck.quack();
        duck.fly();
    }
}

類(lèi)圖

adapter.png

Adapter vs Proxy

  • Adapter實(shí)現(xiàn)一個(gè)接口,使用另外一個(gè)接口;而Proxy實(shí)現(xiàn)同一個(gè)接口;
  • Adapter更強(qiáng)調(diào)Convert轉(zhuǎn)換,需要做額外的工作來(lái)使用另一個(gè)接口;代理是另一個(gè)對(duì)象的占位符,Proxy更強(qiáng)調(diào) 延遲初始化,訪問(wèn)控制等。

參考:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容