適配器模式(java語言實現)

定義

適配器模式將一個類的接口,轉換成客戶期望的另一個接口。 使得原本由於接口不兼容的而不能在一起工作的那些類可以在一起工作。而且不用修改原適配者類的代碼。 wiki: https://en.wikipedia.org/wiki/Adapter_pattern An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Interfaces may be incompatible but the inner functionality should suit the need. The Adapter design pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.

組合模式

這裏寫圖片描述

TwoPlugAdapter.java

package com.immoc.pattern.adapter;
/*
 * 二相轉三相的插座適配器
 */

public class TwoPlugAdapter implements ThreePlugIf {

    private GBTwoPlug plug;

    public TwoPlugAdapter(GBTwoPlug plug){
        this.plug = plug;
    }
    @Override
    public void powerWithThree() {
        System.out.println("通過轉化");
        plug.powerWithTwo();

    }

}

繼承模式

這裏寫圖片描述
TwoPlugAdapterExtends.java

package com.immoc.pattern.adapter;

/*
 * 採用繼承方式的插座適配器
 */
public class TwoPlugAdapterExtends extends GBTwoPlug implements ThreePlugIf {

    @Override
    public void powerWithThree() {
        System.out.print("藉助繼承適配器");
        this.powerWithTwo();

    }

}

Client

NoteBook.java

package com.immoc.pattern.adapter;

public class NoteBook {

    private ThreePlugIf  plug;

    public NoteBook(ThreePlugIf plug){
        this.plug = plug;
    }

    //使用插座充電
    public void charge(){
        plug.powerWithThree();
    }

    public static void main(String[] args) {
        GBTwoPlug two =  new GBTwoPlug();
        ThreePlugIf three = new TwoPlugAdapter(two);
        NoteBook nb = new NoteBook(three);
        nb.charge();


        three = new TwoPlugAdapterExtends();
        nb = new NoteBook(three);
        nb.charge();
    }

}

優點

透明
通過適配器,客戶端可以調用同一接口,因而對客戶端來說是透明的。
這樣更加簡單、直接、緊湊。
重用
複用了現存的類,解決了現存類和複用環境要求不一致的情況。
低耦合
將目標類和適配者類解耦,通過一如一個適配器重用適配者類,
無需修改原有代碼(遵循開閉原則)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章