java23種設計模式-介面卡模式
阿新 • • 發佈:2018-12-13
定義
介面卡模式是把一個類的介面轉換成客戶所期望的另一種介面,從而使原本不匹配而無法在一起工作的兩個類可以一起工作。
UML
角色
- Target: 符合客戶端期望的介面。
- Adaptee: 需要被適配的類。此類包含了客戶端想要實現的大部分功能,但並不能完成客戶端所想完成的所有任務,同時又不能被直接修改,因此需要被適配。
- Adapter: 介面卡類。繼承了Adaptee類的方法,如function1(),同時又實現了Target介面。介面卡使得相互不相容的Target和Adaptee能在Adapter中一起配合完成工作。
類介面卡示例
UML中的表示即為類介面卡的實現
/** * desc : 被適配的類 * Created by tiantian on 2018/10/2 */ public class Adaptee { public void function1() { System.out.println("I'm function1() who can do something, tut not enough."); } }
/**
* desc : 目標介面
* Created by tiantian on 2018/10/2
*/
public interface Target {
void function1();
void function2();
}
/** * desc : 類介面卡 * Created by tiantian on 2018/10/2 */ public class Adapter extends Adaptee implements Target{ @Override public void function2() { System.out.println("I'm function2() who can do another thing."); } }
/** * desc : 測試 * Created by tiantian on 2018/10/2 */ public class Test { public static void main(String[] args) { Target adapter = new Adapter(); adapter.function1(); adapter.function2(); } // I'm function1() who can do something, tut not enough. // I'm function2() who can do another thing. }
物件介面卡示例
物件介面卡實現了Target介面,並組合了被適配類Adaptee類,使之能完成介面所期望的功能。
/**
* desc : 物件介面卡
* Created by tiantian on 2018/10/2
*/
public class Adapter implements Target{
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void function1() {
adaptee.function1();
}
public void function2() {
System.out.println("I'm function2() who can do another thing.");
}
}
總結
實際開發中物件介面卡更為常用,因為就設計原則而言,組合的方式更靈活易用,方便擴充套件。組合的方式實現的物件介面卡可以動態的向Adapter中注入Adatpee子類的物件。而使用繼承的類介面卡則可以覆蓋Adaptee中的實現,具體使用哪種介面卡,還是看具體的業務場景,因地制宜。