輕鬆掌握Java適配器模式_java

來源:互聯網
上載者:User

在電腦編程中,適配器模式(有時候也稱封裝樣式或者封裝)將一個類的介面適配成使用者所期待的。一個適配允許通常因為介面不相容而不能在一起工作的類工作在一起,做法是將類自己的介面包裹在一個已存在的類中。

特點:將兩個不相容的類通過介面實現在一起工作

企業級開發和常用架構中的應用:流介面,例如將字元流轉換為位元組流輸出是用的outputstreamreader

適配器模式分為類適配器和對象適配器:

舉例:電腦只有USB介面,但是鍵盤只有圓口,這時就需要一個適配器,讓鍵盤能輸入資料到電腦

類適配器:

package com.test.adapter;public class Computer { public void show(USB usb){ usb.recive(); System.out.println("電腦顯示輸入的資料"); }  public static void main(String[] args) { Computer c = new Computer(); USB u = new USBAdapter(); c.show(u); }}class KeyBoard{ public void input(){ System.out.println("鍵盤輸入資料"); }}/** * 適配器介面  */interface USB{ public void recive();}/** * 具體的適配器 */class USBAdapter extends KeyBoard implements USB{ public void recive() { System.out.println("我是USB適配器,我使圓口的鍵盤能和USB介面電腦串連"); super.input(); } }

對象適配器:

package com.test.adapter;public class Computer { public void show(USB usb){ usb.recive(); System.out.println("電腦顯示輸入的資料"); }  public static void main(String[] args) { Computer c = new Computer(); KeyBoard k = new KeyBoard(); USB u = new USBAdapter(k); c.show(u); }}class KeyBoard{ public void input(){ System.out.println("鍵盤輸入資料"); }}/** * 適配器介面  */interface USB{ public void recive();}/** * 具體的適配器 */class USBAdapter implements USB{ private KeyBoard k;  public USBAdapter(KeyBoard k) { this.k = k; }  public void recive() { System.out.println("我是USB適配器,我使圓口的鍵盤能和USB介面電腦串連"); k.input(); } }

相對而言,對象適配器通過組合的方式比類適配器通過整合的方式要更靈活,推薦平時使用對象適配器。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.