外觀模式(Facade):是為了解決類與類之間的依賴關系的,像spring一樣,可以將類與類之間的關系配置到配置文件中,而外觀模式就是將他們的
關系放在一個Facade類中,降低了類與類之間的耦合度,該模式中沒有涉及到接口。
##一、uml建模:

##二、代碼實現:
~~~
/**
* 示例:外觀模式,也稱門面模式
*
* 優點:為了解決類與類之間的依賴關系,降低了類與類之間的耦合度
*
* 該模式中沒有涉及到接口
*/
class Memory {
public void startup() {
System.out.println("this is memory startup...");
}
public void shutdown() {
System.out.println("this is memory shutdown...");
}
}
class CPU {
public void startup() {
System.out.println("this is CPU startup...");
}
public void shutdown() {
System.out.println("this is CPU shutdown...");
}
}
/**
* 作為facade,持有Memory、CPU的實例
*
* 任務讓Computer幫咱們處理,我們無需直接和Memory、CPU打交道
*
* 這里有點像去商店里買東西:咱們買東西只需要到商店去買,而無需去生產廠家那里買。
*
* 商店就可以稱為是一個facade外觀(門面)模式。--> 商品都在商店里
*/
class Computer {
private Memory memory;
private CPU cpu;
public Computer() {
memory = new Memory();
cpu = new CPU();
}
public void startup() {
System.out.println("begin to start the computer...");
memory.startup();
cpu.startup();
System.out.println("computer start finished...");
}
public void shutdown() {
System.out.println("begin to close the computer...");
memory.shutdown();
cpu.shutdown();
System.out.println("computer close finished...");
}
}
/**
* 客戶端測試類
*
* @author Leo
*/
public class Test {
public static void main(String[] args) {
Computer computer = new Computer();
computer.startup();
System.out.println("\n");
computer.shutdown();
}
}
~~~
##三、總結
如果我們沒有Computer類,那么,CPU、Memory他們之間將會相互持有實例,產生關系,這樣會造成嚴重的依賴,修改一個類,可能會帶來其他類的修改,這不是咱們想要看到的,有了Computer類,他們之間的關系被放在了Computer類里,這樣就起到了解耦的作用,這就是外觀Facade模式。
- 前言
- (一)策略模式建模與實現
- (二)觀察者模式建模與實現
- (三)裝飾者模式建模與實現
- (四)工廠方法模式建模與實現
- (五)抽象工廠模式建模與實現
- (六)單例模式建模與實現
- (七)命令模式建模與實現
- (八)適配器模式建模與實現
- (九)外觀模式建模與實現
- (十)模板方法模式建模與實現
- (十一)迭代器模式建模與實現
- (十二)組合模式建模與實現
- (十三)狀態模式建模與實現
- (十四)代理模式建模與實現
- (十五)建造者模式建模與實現
- (十六)原型模式建模與實現
- (十七)橋接模式建模與實現
- (十八)責任鏈模式建模與實現
- (十九)備忘錄模式建模與實現
- (二十)解釋器模式建模與實現
- (二十一)享元模式建模與實現
- (二十二)中介者模式建模與實現
- (二十三)訪問者模式建模與實現
- Java設計模式博客全目錄