结构型模式 - 外观模式 (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();
    }
}
相关推荐
人月神话-Lee19 小时前
【图像处理】框架设计——协议、值类型与工程化思维
图像处理·人工智能·ios·设计模式·架构·ai编程·swift
AI大法师19 小时前
Xbox回归经典绿
大数据·设计模式·xbox
老码观察20 小时前
设计模式实战解读(六):装饰器模式——功能增强,不动原代码
java·设计模式·装饰器模式
Doris_20231 天前
代码格式化 使用oxfmt
设计模式·架构·前端框架
Doris_20231 天前
说一说ESLint+Prettier生效的原理
前端·设计模式·架构
Pomelooooo2 天前
把 git commit 这件事,彻底交给 AI ——一个工程化 /git-commit 命令的设计与落地
设计模式
invicinble2 天前
设计模式(类的拓扑结构)(描述总纲)
设计模式·原型模式
invicinble2 天前
设计模式(类的拓扑结构)(为什么会产生设计模式,以及什么是设计模式)
linux·服务器·设计模式
PersonalViolet2 天前
模板方法模式实战:重构Agent工具审批,告别重复代码
设计模式·agent