1. 程式人生 > 實用技巧 >學習筆記-涉及模式之介面卡模式

學習筆記-涉及模式之介面卡模式

一、概念

介面卡模式(Adapter Pattern)是指將一個類的介面轉換成客戶期望的另一個介面,使原本的介面不相容的類可以一起工作,屬於結構型設計模式。

二、實現

需求:實現一個變壓器,將220V交流電轉換成5V直流電

建立220V交流電和5V直流電

1 public class Across220V {
2 
3     public int output220V(){
4         int output = 220;
5         System.out.println("輸出交流電"+ output + "V");
6         return output;
7     }
8 }
public class Direct5V {

    public int output5V(){
        int output = 5;
        System.out.println("輸出直流電V"+ output + "V");
        return output;
    }
}

建立變壓器

 1 public class PowerAdapter {
 2 
 3     private Across220V across220V;
 4 
 5     public PowerAdapter(Across220V across220V) {
 6
this.across220V = across220V; 7 } 8 9 public int change(){ 10 int ac = across220V.output220V(); 11 // 變壓器 12 int dr = ac/44; 13 System.out.println("輸入電壓" + ac + "V,輸出電壓" + dr + "V"); 14 return ac; 15 } 16 }

測試類

1 public class AdapterTest {
2
3 public static void main(String[] args) { 4 Across220V across220V = new Across220V(); 5 PowerAdapter powerAdapter = new PowerAdapter(across220V); 6 powerAdapter.change(); 7 } 8 }

輸出

輸出交流電220V
輸入電壓220V,輸出電壓5V

顧名思義,介面卡模式的主要功能是適配,當引數與介面無法匹配時可以通過介面卡解決。

當然,介面卡模式的應用遠不止如此簡單,這裡只是能讓讀者簡單理解什麼是介面卡模式。

介面卡模式不是設計階段考慮的設計模式,而是為了彌補設計之初的缺陷。