结构型模式 - 外观模式 (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();
    }
}
相关推荐
geovindu1 小时前
python: Null Object Pattern
开发语言·python·设计模式
数据中穿行3 小时前
单例设计模式全方位深度解析
设计模式
程序员Terry4 小时前
还在用 if-else 做兼容?三分钟学会适配器模式,让你的代码更优雅
java·设计模式
zhoupenghui1685 小时前
golang中常用的设计模式举例
设计模式
lichenyang4535 小时前
组件设计模式与通信
前端·javascript·设计模式
lichenyang4536 小时前
React 性能优化组件设计模式与通信
前端·javascript·设计模式
Kel6 小时前
这就是编程:Pi Monorepo 源码深度--解析一个工业级 AI Agent 框架的设计哲学
人工智能·设计模式·架构
geovindu6 小时前
python: Simple Factory Pattern
开发语言·python·设计模式·简单工厂模式
拳打南山敬老院9 小时前
你的 Agent 可能并不需要过度工程化:一次从 LangGraph 到极简 Agent 的架构反思
人工智能·设计模式
萌小鱼要阳光10 小时前
八种常见的设计模式
设计模式