1. 程式人生 > >門面模式 Facade Pattern

門面模式 Facade Pattern

一、定義:

門面模式(Facade Pattern),是指提供一個統一的介面去訪問多個子系統的多個不同的介面,它為子系統中的一組介面提供一個統一的高層介面。使得子系統更容易使用。

二、門面模式的作用:

參考文章: The facade pattern (also spelled façade) is a software-design pattern commonly used with object-oriented programming. Analogous to a facade in architecture, a facade is an object that serves as a front-facing interface masking more complex underlying or structural code. A facade can:

1、improve the readability and usability of a software library by masking interaction with more complex components behind a single (and often simplified) API; 2、provide a context-specific interface to more generic functionality (complete with context-specific input validation); 3、serve as a launching point for a broader refactor of monolithic or tightly-coupled systems in favor of more loosely-coupled code;

Developers often use the facade design pattern when a system is very complex or difficult to understand because the system has a large number of interdependent classes or because its source code is unavailable. This pattern hides the complexities of the larger system and provides a simpler interface to the client. It typically involves a single wrapper class that contains a set of members required by the client. These members access the system on behalf of the facade client and hide the implementation details.

簡而言之就是門面模式主要有三個作用: 提高了可讀性和可用性,遮蔽系統內部複雜的邏輯; 提供了一個更通用的介面; 支援更多鬆散耦合程式碼;

三、UML圖:

在這裡插入圖片描述

客戶端的呼叫變得非常簡單明瞭。

四、設計模式使用例項:

1、設計組成一臺電腦的各個元件:
/*
 *  電腦CPU
 */
public class CPU {

    public void freeze() {

        //...

    }

    public void jump(long position) {

        //...

    }

    public void execute() {

        //...}

    }

}
/*
 *  硬體驅動
 */
class HardDrive {
    public byte[] read(long lba, int size) {
        //...
    }
}
/*
 *  記憶體
 */
class Memory {
    public void load(long position, byte[] data) { ... }
}

2、抽取一個門面介面,便於擴充套件(不僅僅在於電腦的啟動,手機和Pad亦然如此)
/*
 *  抽取一個門面介面
 */

interface IComputerFacede{

    public void start();

}
3、實現真正被客戶端呼叫的門面物件

/*
 *  門面物件
 */

class ComputerFacade implements IComputerFacede {
    private CPU cpu;
    private Memory memory;
    private HardDrive hardDrive;

    public ComputerFacade() {
        this.cpu = new CPU();
        this.memory = new Memory();
        this.hardDrive = new HardDrive();
    }

    public void start() {
        cpu.freeze();
        memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
        cpu.jump(BOOT_ADDRESS);
        cpu.execute();
    }
}
4、客戶端呼叫
/*
 *  客戶端呼叫
 */
class Client {

    /* 只要簡單的一個呼叫,就可以完成電腦的啟動,無需瞭解內部邏輯 */
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        computer.start();
    }
}

總結:由案例可以輕鬆的看出來,客戶端僅需要和門面物件進行互動,無需瞭解計算機真正的啟動流程,在降低系統耦合性的同時,也保障了內部系統的邏輯安全