设计模式之:门面模式

    xiaoxiao2021-03-25  79

    门面模式定义: 门面模式要求一个子系统的外部与其内部的通信必须通过一个统一的门面(Facade)对象进行。门面模式提供一个高层次的接口,使得子系统更易于使用。

    使用场景: 1.为一个复杂的模块或子系统提供一个供外界访问的接口。 2.子系统相对独立——外界对子系统的访问只要黑箱操作即可。 门面模式是一种最常用的封装模式,就算你压根不懂设计模式,也肯定用过门面模式。

    下面是一个抽象出来的例子,一个客户端(你)是怎样通过一个 facade(计算机)来访问一个复杂的系统(计算机的内部,比如说 CPU 和硬盘驱动器)。 // 复杂的部分

    class CPU { public void freeze() { ... } public void jump(long position) { ... } public void execute() { ... } } class Memory { public void load(long position, byte[] data) { ... } } class HardDriver { public byte[] read(long lba, int size) { ... } } // Facade class ComputerFacade { private CPU processor; private Memory ram; private HardDriver hd; public ComputerFacade() { this.processor = new CPU(); this.ram = new Memory(); this.hd = new HardDriver(); } public void start() { processor.freeze(); ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE)); processor.jump(BOOT_ADDRESS); processor.execute(); } } // Client class You { public static void main(String[] args) { ComputerFacade computer = new ComputerFacade(); computer.start(); } }
    转载请注明原文地址: https://ju.6miu.com/read-39616.html

    最新回复(0)