Java設(shè)計(jì)模式之外觀模式的實(shí)現(xiàn)方式
什么是外觀模式?
外觀模式(Facade Pattern)隱藏系統(tǒng)的復(fù)雜性,并向客戶端提供了一個(gè)客戶端可以訪問系統(tǒng)的接口。這種類型的設(shè)計(jì)模式屬于結(jié)構(gòu)型模式,它向現(xiàn)有的系統(tǒng)添加一個(gè)接口,來隱藏系統(tǒng)的復(fù)雜性。 這種模式涉及到一個(gè)單一的類,該類提供了客戶端請求的簡化方法和對現(xiàn)有系統(tǒng)類方法的委托調(diào)用。
實(shí)例說明
現(xiàn)在有一個(gè)回家打開燈,打開空調(diào),使用電腦的場景??梢允褂猛庥^模式設(shè)計(jì),燈、空調(diào)和電腦都是子系統(tǒng)
三個(gè)子系統(tǒng)類
public class Computer {
public void on(){
System.out.println("打開電腦");
}
public void off(){
System.out.println("關(guān)閉電腦");
}
}
public class Light {
public void on(){
System.out.println("打開燈");
}
public void off(){
System.out.println("關(guān)閉燈");
}
}
public class AirConditioning {
public void on(){
System.out.println("打開空調(diào)");
}
public void off(){
System.out.println("關(guān)閉空調(diào)");
}
}
如果不適用外觀模式
客戶端類
public class Client {
public static void main(String[] args) {
AirConditioning airConditioning = new AirConditioning();
Computer computer = new Computer();
Light light = new Light();
//所有子系統(tǒng)打開
light.on();
airConditioning.on();
computer.on();
//所有子系統(tǒng)關(guān)閉
computer.off();
airConditioning.off();
light.off();
}
}
子系統(tǒng)和客戶端耦合,每當(dāng)子系統(tǒng)有改變,都需要修改客戶端
當(dāng)使用外觀模式
外觀類
public class RoomFacade {
AirConditioning airConditioning;
Light light;
Computer computer;
public RoomFacade(){
airConditioning = new AirConditioning();
light = new Light();
computer = new Computer();
}
public void on(){
light.on();
airConditioning.on();
computer.on();
}
public void off(){
computer.off();
airConditioning.off();
light.off();
}
}
接下來客戶端只需要和外觀類交互即可,不用知道子系統(tǒng)內(nèi)部的實(shí)現(xiàn)
客戶端類
public class Client {
public static void main(String[] args) {
RoomFacade facade = new RoomFacade();
facade.on();
facade.off();
}
}
可見客戶端想使用子系統(tǒng)十分簡單
使用場景
- 為復(fù)雜的模塊或子系統(tǒng)提供外界訪問的模塊。
- 子系統(tǒng)相對獨(dú)立。
- 預(yù)防低水平人員帶來的風(fēng)險(xiǎn)。
外觀模式的優(yōu)缺點(diǎn)
優(yōu)點(diǎn)
- 客戶端不與系統(tǒng)耦合。雖然外觀類和系統(tǒng)耦合,但是客戶端不與系統(tǒng)耦合,如果增加子系統(tǒng),并不需要修改客戶端,只需要修改外觀類。
- 簡單易用。客戶端不需要了解子系統(tǒng)內(nèi)部實(shí)現(xiàn),只需要和外觀類交互即可,調(diào)用起來非常簡單。
缺點(diǎn)
- 如果設(shè)計(jì)不當(dāng),增加新的子系統(tǒng)可能需要修改外觀類源代碼,違反開閉原則。
到此這篇關(guān)于Java設(shè)計(jì)模式之外觀模式的實(shí)現(xiàn)方式的文章就介紹到這了,更多相關(guān)Java外觀模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java多線程案例實(shí)戰(zhàn)之定時(shí)器的實(shí)現(xiàn)
在Java中可以使用多線程和定時(shí)器來實(shí)現(xiàn)定時(shí)任務(wù),下面這篇文章主要給大家介紹了關(guān)于Java多線程案例之定時(shí)器實(shí)現(xiàn)的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(60)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望可以幫到你2021-08-08
淺析如何利用Spring AI構(gòu)建一個(gè)簡單的問答系統(tǒng)
sentinel?整合spring?cloud限流的過程解析
Java實(shí)現(xiàn)將圖片上傳到webapp路徑下 路徑獲取方式
SpringBoot后端接收數(shù)組對象的實(shí)現(xiàn)
基于SpringBoot+FFmpeg+ZLMediaKit實(shí)現(xiàn)本地視頻推流

