结构型模式 - 外观模式 (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();
    }
}
相关推荐
全栈前端老曹3 小时前
【Redis】发布订阅模型 —— Pub/Sub 原理、消息队列、聊天系统实战
前端·数据库·redis·设计模式·node.js·全栈·发布订阅模型
资深web全栈开发4 小时前
设计模式之桥接模式 (Bridge Pattern)
javascript·设计模式·桥接模式
小温冲冲16 小时前
通俗且详细讲解模板方法模式
设计模式·模板方法模式
reddingtons19 小时前
Magnific AI:拒绝“马赛克”?AI 幻觉重绘流,拯救 1024px 废片
图像处理·人工智能·设计模式·新媒体运营·aigc·设计师·教育电商
知无不研20 小时前
c++的设计模式(常用)
c++·观察者模式·单例模式·设计模式·简单工厂模式
李广坤1 天前
设计模式的本质:隔离变化
后端·设计模式
河码匠1 天前
设计模式之依赖注入(Dependency Injection)
java·设计模式·log4j
小湘西1 天前
互联网黑话持续更新
其他·设计模式
a3535413821 天前
设计模式——访问者模式
设计模式·访问者模式
Eloudy1 天前
动态库中不透明数据结构的设计要点总结
数据结构·设计模式