Java設計模式之-外觀模式

Java設計模式之-外觀模式

外觀模式是爲了解決類與類之間的依賴關係的,像spring一樣,可以將類和類之間的關係配置到配置文件中,而外觀模式就是將他們的關係放在一個Facade類中,降低了類類之間的耦合度,該模式中沒有涉及到接口,看下類圖:(我們以一個計算機的啓動過程爲例)

這裏寫圖片描述

下面請看示例代碼:

public class FacadeTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Computer computer=new Computer();
        computer.start();
        computer.shutdown();
    }

}

class CPU
{
    public void startup(){
        System.out.println("this is cpu startup");
    }
    public void shutdown(){
        System.out.println("this is cpu shutdown");
    }
}

class Memory
{
    public void startup(){
        System.out.println("this is memory startup");
    }
    public void shutdown(){
        System.out.println("this is memory shutdown");
    }
}

class Disk{
    public void startup(){
        System.out.println("this is disk startup");
    }
    public void shutdown(){
        System.out.println("this is disk shutdown");
    }
}

class Computer
{
    private CPU cpu;
    private Memory memory;
    private Disk disk;

    public Computer(){
        this.cpu=new CPU();
        this.memory=new Memory();
        this.disk=new Disk();
    }
    public void start(){
        System.out.println("start the computer");
        cpu.startup();
        memory.startup();
        disk.startup();
        System.out.println("start the computer finished");
    }
    public void shutdown(){
        System.out.println("begin to close the computer");
        cpu.shutdown();
        memory.shutdown();
        disk.shutdown();
        System.out.println("close the computer finished");
    }
}

輸出結果:

start the computer
this is cpu startup
this is memory startup
this is disk startup
start the computer finished
begin to close the computer
this is cpu shutdown
this is memory shutdown
this is disk shutdown
close the computer finished

如果我們沒有Computer類,那麼,CPU、Memory、Disk他們之間將會相互持有實例,產生關係,這樣會造成嚴重的依賴,修改一個類,可能會帶來其他類的修改,這不是我們想要看到的,有了Computer類,他們之間的關係被放在了Computer類裏,這樣就起到了解耦的作用,這,就是外觀模式!

發佈了61 篇原創文章 · 獲贊 7 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章