- 外觀模式又稱為門面模式,是一種通過(guò)為多個(gè)復(fù)雜的子系統(tǒng)提供一個(gè)一致的接口,而使這些子系統(tǒng)更加容易被訪問(wèn)的模式雷绢。該模式對(duì)外有一個(gè)統(tǒng)一的接口,外部應(yīng)用程序不用關(guān)系內(nèi)部子系統(tǒng)的具體的細(xì)節(jié)理卑,這樣會(huì)大大降低應(yīng)用程序的復(fù)雜程度翘紊,提高程序的可維護(hù)性。
結(jié)構(gòu)
- 外觀(Facade)角色:為多個(gè)子系統(tǒng)對(duì)外提供一個(gè)共同的接口藐唠;
- 子系統(tǒng)(Sub System)角色:實(shí)現(xiàn)系統(tǒng)的部分功能帆疟,客戶可以通過(guò)外觀
實(shí)例
- 智能家居控制房屋內(nèi)設(shè)備的開關(guān)。
public class Light {
public void on(){
System.out.println("打開電燈");
}
public void off(){
System.out.println("關(guān)閉電燈");
}
}
public class AirCondition {
public void on(){
System.out.println("打開空調(diào)");
}
public void off(){
System.out.println("關(guān)閉空調(diào)");
}
}
public class TV {
public void on(){
System.out.println("打開電視機(jī)");
}
public void off(){
System.out.println("關(guān)閉電視機(jī)");
}
}
public class SmartAppliancesFacade {
private Light light;
private TV tv;
private AirCondition airCondition;
public SmartAppliancesFacade() {
light = new Light();
tv = new TV();
airCondition = new AirCondition();
}
// 通過(guò)語(yǔ)音控制
public void say(String msg){
if(msg.contains("打開")){
on();
}else if(msg.contains("關(guān)閉")){
off();
}else{
System.out.println("我還聽不懂你在說(shuō)什么");
}
}
// 一鍵打開功能
private void on(){
light.on();
tv.on();
airCondition.on();
}
// 一鍵關(guān)閉功能
private void off(){
light.off();
tv.off();
airCondition.off();
}
}
public class Client {
public static void main(String[] args) {
SmartAppliancesFacade facade = new SmartAppliancesFacade();
facade.say("打開家電");
System.out.println("=======================");
facade.say("關(guān)閉家電");
}
}