總章目錄,設(shè)計(jì)模式(一)基本介紹
一墩虹、定義
適配器模式:將一個(gè)類(lèi)的接口變換成客戶端所期待的另一種接口航厚,從而使原本接口不匹配而無(wú)法一起工作的兩個(gè)類(lèi)能夠在一起工作。
適配器:類(lèi)適配器气忠、對(duì)象適配器
二邻储、類(lèi)適配器
類(lèi)適配器模式是把適配的類(lèi)的API轉(zhuǎn)換成為目標(biāo)類(lèi)的API,UML如下圖所示:
客戶端(Client):客戶只會(huì)看到目標(biāo)接口
目標(biāo)(Target)接口:當(dāng)前系統(tǒng)業(yè)務(wù)所期待的接口旧噪,它可以是抽象類(lèi)或接口吨娜。
適配者(Adaptee)類(lèi):它是被訪問(wèn)和適配的現(xiàn)存組件庫(kù)中的組件接口。
適配器(Adapter)類(lèi):它是一個(gè)轉(zhuǎn)換器淘钟,通過(guò)繼承或引用適配者的對(duì)象宦赠,把適配者接口轉(zhuǎn)換成目標(biāo)接口,讓客戶按目標(biāo)接口的格式訪問(wèn)適配者
Target:
public interface Target {
void Request();
}
Adaptee適配者:
public class Adaptee {
public void SpecificRequest(){
System.out.println("適配者接口米母!");
}
}
Adapter適配器
public class Adapter extends Adaptee implements Target {
@Override
public void Request() {
this.SpecificRequest();
}
}
我們注意到Adaptee 中沒(méi)有Request()
方法勾扭,因此我們使用補(bǔ)充適配器這個(gè)方法。
public class Client {
public static void main(String[] args){
Target target = new Adapter();
target.Request();
}
}
輸出:
適配者接口爱咬!
三尺借、對(duì)象適配器
對(duì)象適配器與類(lèi)的適配器模式相同,對(duì)象的適配器模式把適配的類(lèi)的API轉(zhuǎn)換成為目標(biāo)類(lèi)的API精拟。
public interface Target {
void Request();
}
public class Adaptee {
public void SpecificRequest(){
System.out.println("適配者接口燎斩!");
}
}
public class Adapter implements Target {
// 直接關(guān)聯(lián)被適配類(lèi)
private Adaptee adaptee;
// 可以通過(guò)構(gòu)造函數(shù)傳入具體需要適配的被適配類(lèi)對(duì)象
public Adapter (Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void Request() {
// 這里是使用委托的方式完成特殊功能
this.adaptee.SpecificRequest();
}
}
public class Client {
public static void main(String[] args){
Target target = new Adapter(new Adaptee());
target.Request();
}
}
四、總結(jié)
名稱(chēng) | 優(yōu)點(diǎn) | 缺點(diǎn) |
---|---|---|
類(lèi)適配器 | 復(fù)用性好蜂绎,客戶端可以調(diào)用同一接口栅表,耦合性低。 | 高耦合师枣,靈活性低 |
對(duì)象適配器 | 靈活性高怪瓶、低耦合 | 需要引入對(duì)象實(shí)例 |
通常我們會(huì)使用對(duì)象適配器模式,避免使用繼承践美。