Skip to content

外观模式

字数: 0 字 时长: 0 分钟

简介

外观模式(Facade Pattern)核心思想是:为复杂的子系统提供一个统一的对外接口

UML 类图

facade.webp

  • 外观类(Facade):对外提供统一接口,封装子系统的调用
  • 子系统类(SubSystem):子系统类,提供子系统的功能

实现示例

利用外观模式屏蔽计算机启动过程系统内部的复杂性,只对外部暴露一个统一接口

java
// 1. 子系统组件 --- CPU
class CPU {
    public void start() {
        System.out.println("CPU 启动");
    }
    public void execute(String command) {
        System.out.println("CPU执行指令: " + command);
    }
}

// 2. 子系统组件 --- 内存
class Memory {
    public void load(long pos, byte[] data) {
        System.out.println("内存加载数据到位置:" + pos);
    }
}

// 3. 子系统组件 --- 硬盘驱动
class HardDrive {
    public byte[] read(long pos, int size) {
        System.out.println("从硬盘读取扇区" + lba);
        return new byte[size];
    }
}

// 4. 外观类 (计算机启动器)
class ComputerFacade {
    private final CPU cpu;
    private final Memory memory;
    private final HardDrive hardDrive;
    public ComputerFacade() {
        cpu = new CPU();
        memory = new Memory();
        hardDrive = new HardDrive();
    }
    // 计算机启动过程
    public void start() {
        // cpu 启动
        cpu.start();
        // 加载引导程序
        byte[] bootData = hardDrive.read(0,1024);
        memory.load(0,bootData);
        // 执行引导程序
        cpu.execute("BOOT");
    }
}

// 5. 调用示例
public static void main(String[] args) {
    ComputerFacade computer = new ComputerFacade();
    // 客户端无需关心系统内部复杂流程
    computer.start();
}