结构型模式 - 外观模式 (Facade)

结构型模式 - 外观模式 (Facade)

又名门面模式,通过为多个子系统提供一个一致的接口,使得子系统使用起来更加容易.

外观模式是"迪米特法则"的典型应用.


java 复制代码
// CPU 类,代表 CPU 子系统
class CPU {
    public void start() {
        System.out.println("CPU 启动");
    }

    public void shutDown() {
        System.out.println("CPU 关闭");
    }
}

// 内存类,代表内存子系统
class Memory {
    public void load() {
        System.out.println("内存加载");
    }

    public void unload() {
        System.out.println("内存卸载");
    }
}

// 硬盘类,代表硬盘子系统
class HardDrive {
    public void read() {
        System.out.println("硬盘读取");
    }

    public void stopReading() {
        System.out.println("硬盘停止读取");
    }
}

// 电脑外观类,封装子系统操作
class ComputerFacade {
    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 startComputer() {
        cpu.start();
        memory.load();
        hardDrive.read();
        System.out.println("电脑开机完成");
    }

    // 关机方法,调用子系统的关闭操作
    public void shutDownComputer() {
        hardDrive.stopReading();
        memory.unload();
        cpu.shutDown();
        System.out.println("电脑关机完成");
    }
}

// 客户端代码
public class ComputerFacadeExample {
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        // 开机
        computer.startComputer();
        System.out.println();
        // 关机
        computer.shutDownComputer();
    }
}
相关推荐
泯仲1 小时前
Ragent项目7种设计模式深度解析:从源码看设计模式落地实践
java·算法·设计模式·agent
WarrenMondeville3 小时前
1.Unity面向对象-单一职责原则
unity·设计模式·c#
bmseven3 小时前
23种设计模式 - 适配器模式(Adapter)
设计模式·适配器模式
bmseven4 小时前
23种设计模式 - 组合模式(Composite)
设计模式·组合模式
MarkHD6 小时前
RPA工程化实践:三种核心设计模式让复杂流程优雅可控
linux·设计模式·rpa
AI大法师6 小时前
字标Logo设计指南:中文品牌如何用字体做出高级感与辨识度
人工智能·设计模式
Yu_Lijing7 小时前
基于C++的《Head First设计模式》笔记——中介者模式
笔记·设计模式·中介者模式
程序员小寒8 小时前
JavaScript设计模式(四):发布-订阅模式实现与应用
开发语言·前端·javascript·设计模式
是糖糖啊9 小时前
Agent 不好用?先别怪模型,试试 Harness Engineering
人工智能·设计模式
jiankeljx9 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式