適配器模式簡介
- 適配器模式是作為兩個不兼容的接口之間的橋梁堵漱。這種類型的設(shè)計模式屬于結(jié)構(gòu)型模式夜牡,它結(jié)合了兩個獨立接口的功能芳誓。
- 這種模式涉及到一個單一的類醉锅,該類負責加入獨立的或不兼容的接口功能兔簇。
類模式
要被適配的類TV和類Wire
//要被適配的類:電視
public class TV {
//電視劇需要一個電源適配器,就可以供電,開機
public void open(IPowerAdapter iPowerAdapter) {
//打開電視垄琐,需要電边酒,需要連接電線,需要一個電源適配器
iPowerAdapter.power();
}
}
//要被適配接入的類:電線
public class Wire {
public void supply() {
System.out.println("供上電了...");
}
}
電源適配器接口IPowerAdapter
//電源適配器接口
public interface IPowerAdapter {
//供電
void power();
}
電線和電視機適配器類TVPowerAdapter(通過繼承方式)
//真正的適配器狸窘,一端連接電線墩朦,一端連接電視
public class TVPowerAdapter extends Wire implements IPowerAdapter {
@Override
public void power() {
super.supply();//有電了
}
}
測試類
public class Test {
public static void main(String[] args) {
TV tv = new TV();//電視
TVPowerAdapter tvPowerAdapter = new TVPowerAdapter();//電源適配器
Wire wire = new Wire();//電線
tv.open(tvPowerAdapter);
/**
* 輸出結(jié)果:
* 供上電了...
*/
}
}
測試結(jié)果
供上電了...
組合模式(推薦使用)
要被適配的類TV和類Wire
//要被適配的類:電視
public class TV {
//電視劇需要一個電源適配器,就可以供電翻擒,開機
public void open(IPowerAdapter iPowerAdapter) {
//打開電視氓涣,需要電,需要連接電線韭寸,需要一個電源適配器
iPowerAdapter.power();
}
}
//要被適配接入的類:電線
public class Wire {
public void supply() {
System.out.println("供上電了...");
}
}
電源適配器接口IPowerAdapter
//電源適配器接口
public interface IPowerAdapter {
//供電
void power();
}
電線和電視機適配器類TVPowerAdapter(通過組合方式)
//真正的適配器春哨,一端連接電線,一端連接電視
public class TVPowerAdapter implements IPowerAdapter {
private Wire wire;
public TVPowerAdapter(Wire wire) {
this.wire = wire;
}
@Override
public void power() {
wire.supply();//有電了
}
}
測試類
public class Test {
public static void main(String[] args) {
TV tv = new TV();//電視
Wire wire = new Wire();//電線
TVPowerAdapter tvPowerAdapter = new TVPowerAdapter(wire);//電源適配器
tv.open(tvPowerAdapter);
/**
* 輸出結(jié)果:
* 供上電了...
*/
}
}
測試結(jié)果
供上電了...