簡單介紹介面卡設計模式(內含程式碼分析)
阿新 • • 發佈:2018-12-02
介面卡(Adapter Pattern) 就是有一個已有的類,但是這個類的介面和你的不一樣,不能直接拿來使用,這個時候就需要使用介面卡來幫你了.
介面卡的三個特點 :
介面卡物件實現原有介面
介面卡物件組合一個實現新介面的物件(這個物件也可以不實現一個介面,只是一個單純物件)
對介面卡原有介面方法的呼叫被委託給新介面的例項的特定的方法
模擬的場景 : 買了一個英標插頭的外掛(電器,使用3個插頭的),但是國內的插座都是兩個插頭的,此時,就需要一個轉介面使得在英標插頭的電器也可以在國內進行充電,此時需要藉助的是介面卡設計模式
UML圖 :
步驟 :
1 建立一個國際介面以及它的實現類
1 /** 2 * @Author : zhuhuicong 3 * 2018/12/2 15:29 4 * @Version 1.0 5 * 國際插頭 6 */ 7 public interface CnPlugInterface { 8 void chargewith2Pins(); //國際插頭只能使用兩個角的 9 } 10 11 public class CnPlugin implements CnPlugInterface { 12 @Override 13 public void chargewith2Pins() {View Code14 System.out.println("使用兩個角的插座充電"); 15 } 16 }
2建立一個英標的介面以及它的實現類
1 /** 2 * @Author : zhuhuicong 3 * 2018/12/2 15:34 4 * @Version 1.0 5 * 英標插頭 6 */ 7 public interface EnPluginInterface { 8 void chargeWith3Pins(); //英標插頭使用的是3個角的充電 9 } 10 11 public class EnPlugin implementsView CodeEnPluginInterface { 12 @Override 13 public void chargeWith3Pins() { 14 System.out.println("使用3個角的插座充電"); 15 } 16 }
3模擬一個Home類(模擬一個在國內的家庭,只能使用國際插頭)
1 /** 2 * @Author : zhuhuicong 3 * 2018/12/2 15:30 4 * @Version 1.0 5 * 模仿在家充電的過程 6 */ 7 public class Home { 8 private CnPlugInterface cnPlug; 9 10 public Home() { 11 } 12 13 public Home(CnPlugInterface cnPlug) { 14 this.cnPlug = cnPlug; 15 } 16 17 public void setCnPlug(CnPlugInterface cnPlug) { 18 this.cnPlug = cnPlug; 19 } 20 21 public void charge(){ 22 cnPlug.chargewith2Pins(); //國際充電是使用的是2個角的 23 } 24 }View Code
4新建一個介面卡Adapter,功能是實現英標插頭對國際插頭的轉換:
1 /** 2 * @Author : zhuhuicong 3 * 2018/12/2 15:37 4 * @Version 1.0 5 * 介面卡要求 : 6 * 1 介面卡必須實現原有舊的介面 7 * 2 介面卡物件中持有對新介面的引用,當呼叫就介面時,將這個呼叫委託給實現新介面的物件 8 * 來處理,也就是在介面卡物件中組合一個新介面 9 */ 10 public class PluginAdapter implements CnPlugInterface{ 11 private EnPluginInterface enPlugin; 12 13 public PluginAdapter() { 14 } 15 16 public PluginAdapter(EnPluginInterface enPlugin) { 17 this.enPlugin = enPlugin; 18 } 19 20 //介面卡實現了英標的插頭,然後過載國際的充電方法為英標的方法 21 @Override 22 public void chargewith2Pins() { 23 enPlugin.chargeWith3Pins(); 24 } 25 }View Code
5新建一個測試類進行模擬場景:
1 /** 2 * @Author : zhuhuicong 3 * 2018/12/2 15:40 4 * @Version 1.0 5 */ 6 public class AdapterTest { 7 public static void main(String[] args) { 8 EnPluginInterface enPlugin = new EnPlugin(); //模擬的場景是買了個英標插頭的外掛 9 Home home = new Home(); //模擬在國內的家庭 10 PluginAdapter pluginAdapter = new PluginAdapter(enPlugin); //使用介面卡,轉介面 11 home.setCnPlug(pluginAdapter); 12 home.charge(); //呼叫充電的方法 13 } 14 }View Code
註明 : 以上整理的資料均來自實驗樓學習網站.......