结构型模式 - 外观模式 (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();
    }
}
相关推荐
阿闽ooo2 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4962 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃2 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20102 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈2 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||3 天前
安装依赖三方exe/msi的软件设计模式
设计模式
希望_睿智3 天前
实战设计模式之访问者模式
c++·设计模式·架构
茶本无香3 天前
设计模式之十六:状态模式(State Pattern)详解 -优雅地管理对象状态,告别繁琐的条件判断
java·设计模式·状态模式
驴儿响叮当20103 天前
设计模式之备忘录模式
设计模式·备忘录模式
驴儿响叮当20103 天前
设计模式之迭代器模式
设计模式·迭代器模式