Facade Pattern

The Facade design pattern is often used when a system is very complex or difficult to understand because the system has a large number of interdependent classes or its source code is unavailable. This pattern hides the complexities of the larger system and provides a simpler interface to the client.

Intent

  • Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
  • Wrap a complicated subsystem with a simpler interface.

Implementation

Class Diagram of Facade Pattern

This is an abstract example of how a client interacts with a facade (the "computer") to a complex system (internal computer parts, like CPU and HardDrive).

// CPU.java
class CPU {
    public void freeze() {
        System.out.println("CPU: freezing...");
    }

    public void jump(long position) {
        System.out.println("CPU: jumping...");
    }

    public void execute() {
        System.out.println("CPU: executing...");
    }
}
// HardDrive.java
public class HardDrive {
    public byte[] read(long lba, int size) {
        System.out.println("HardDrive: reading...");
        return null;
    }
}
// Memory.java
public class Memory {
    public void load(long position, byte[] data) {
        System.out.println("Memory: loading... " );
    }
}
// ComputerFacade.java
public class ComputerFacade {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;

    public ComputerFacade() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }

    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }

    // Dummy values for simplicity
    static long BOOT_ADDRESS = 0;
    static long BOOT_SECTOR = 0;
    static int SECTOR_SIZE = 0;
}
// ClientMain.java
public class ClientMain {
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        computer.start();
    }
}

Output:

CPU: freezing...
HardDrive: reading...
Memory: loading...
CPU: jumping...
CPU: executing...

Reference

Wikipedia
Hackjustu Dojo (my blog)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 这会不那么忙,抽空谢谢让我感动到无话可说的群。 大家微信圈里群很多吧,你经常看的是哪个,这个群是我唯一一个任何一条...
    Brena阅读 2,642评论 0 0
  • 小时候觉得孤独是一件很酷的事情,长大了觉得孤独是一件很凄凉的事情。现在,孤独不是一件事情。 饭局上,酒过三旬,一个...
    我是东北仁儿阅读 1,603评论 0 1
  • 更新完成回到家里,发现是到了老家。刚刚建造的新房子下面有一个大坑,整个房子陷进了坑里面,像是被挤扁的易拉罐一样,整...
    问颜阅读 1,427评论 0 0
  • 01 孩子上高三的第二学期,学校为学生要举行一个“成人礼”。其实我的孩子已经过了18岁生日,彼时已经是18岁...
    虹姐有话说阅读 4,873评论 0 0
  • 翌日,子轩上午九时回到拳馆,却见一人站在招待处前,正与助手争论。这时段应该很少人学拳。他没有理会,径自走到更衣室去...
    迷人来稿阅读 2,865评论 0 0

友情链接更多精彩内容