設計模式之—適配器模式


1.適配器模式的定義

Adapter Pattern:Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because of incompatible interface.

將一個類的接口變換成客戶端所期待的另一種接口,從而使原本因接口不匹配而無法在一起工作的兩個類能夠一起工作。

2.通用類圖

適配器模式中有三個主要對象。

Target:

轉換成的目標接口,即將其他類轉換為此Target接口

Adaptee:

被轉換的類

Adapter:

適配器,通過實現Target接口並繼承Adaptee類,並重寫Target接口方法來實現適配

類圖如下:

實現代碼如下:
Target類:

public interface Target {

    /**
     * request
     */
    void request();
}

Adaptee類:

public class Adaptee {

    public void doSomething(){
        System.out.println("Do something!");
    }
}

Adapter類:

public class Adapter extends Adaptee implements Target {

    @Override
    public void request() {
        doSomething();
    }
}

Client類:

public class Client {

    public static void main(String[] args) throws Exception {
        Target target = new Adapter();
        target.request();
    }
}

3.優點

1.可以使兩個無關聯的類一起運行
2.靈活性好,當不需要此適配器的時候,只需要將此類摘除掉即可

4.總結

適配器模式通常用來解決在功能變動時,解決接口不相容的問題,在系統設計階段不應該使用此中模式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM