設計模式–適配器(Adapter)

來源:互聯網
上載者:User

 

適配器模式概述
    將一個類的介面轉換成客戶希望的另外一個介面。Adapter模式使得原本由於介面不相容而不能一起工作的那些類可以一起工作。
適用性
    1.你想使用一個已經存在的類,而它的介面不符合你的需求。    2.你想建立一個可以複用的類,該類可以與其他不相關的類或不可預見的類(即那些介面      可能不一定相容的類)協同工作。    3.(僅適用於對象Adapter)你想使用一些已經存在的子類,但是不可能對每一個都進行      子類化以匹配它們的介面。對象適配器可以適配它的父類介面。
參與者
    1.Target      定義Client使用的與特定領域相關的介面。    2.Client      與符合Target介面的對象協同。    3.Adaptee      定義一個已經存在的介面,這個介面需要適配。    4.Adapter      對Adaptee的介面與Target介面進行適配
Example
Target public interface Target {    void adapteeMethod();        void adapterMethod();}Adaptee public class Adaptee {    public void adapteeMethod() {        System.out.println("Adaptee method!");    }}Adapter public class Adapter implements Target {    private Adaptee adaptee;        public Adapter(Adaptee adaptee) {        this.adaptee = adaptee;    }public void adapteeMethod() {adaptee.adapteeMethod();}public void adapterMethod() {System.out.println("Adapter method!");    }}Client public class Test {    public static void main(String[] args) {        Target target = new Adapter(new Adaptee());        target.adapteeMethod();                target.adapterMethod();    }}result Adaptee method!Adapter method!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.