结构型模式 - 外观模式 (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();
    }
}
相关推荐
C7211BA14 小时前
GoF提出的经典设计模式
设计模式
willxiao15 小时前
js 单例模式 6 种实现方式
javascript·设计模式
SoulRoar.17 小时前
设计模式原理
设计模式
weixin_5214311219 小时前
设计模式一览表
设计模式
ZouZou老师20 小时前
C++设计模式之抽象工厂模式:以家具生产为例
c++·设计模式·抽象工厂模式
阿波罗尼亚20 小时前
Head First设计模式(十一) 设计原则 代理模式
设计模式·代理模式
ZouZou老师21 小时前
C++设计模式之单例模式:以小区快递柜为例
c++·单例模式·设计模式
AM越.21 小时前
Java设计模式超详解——抽象工厂设计模式(含UML图)
java·设计模式·uml
职业码农NO.121 小时前
智能体AI的六大核心设计模式,很常见
人工智能·设计模式·系统架构·aigc·rag
小鱼小鱼.oO21 小时前
Agent 设计模式
设计模式