结构型模式 - 外观模式 (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();
    }
}
相关推荐
Shadow(⊙o⊙)8 小时前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki1 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅661 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa1 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio
sarasuki1 天前
如何让 Agent 获取更多的能力?插件 / 技能系统
人工智能·设计模式·agent
sarasuki1 天前
如何让 Agent 安全运行你的命令 :命令分级 + Hook + 读写锁
人工智能·设计模式·agent
Zane19941 天前
技术不难,为什么项目却越改越不敢动?聊聊复杂系统开发该怎么想
设计模式
geovindu1 天前
rust: Factory Method Pattern
开发语言·设计模式·rust·工厂方法模式·创建型模式
一木 之林2 天前
第 8 节 C++ 设计模式在 AI 推理 SDK 和 Agent 工具运行时中如何落地
c++·人工智能·设计模式
Zane19942 天前
MVC 三层架构被打上反模式标签?一次账户扣款需求,讲清楚贫血模型和充血模型该怎么选
设计模式