结构型模式 - 外观模式 (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();
    }
}
相关推荐
砍光二叉树4 小时前
【设计模式】行为型-中介者模式
设计模式·中介者模式
sanzk8 小时前
工厂方法模式
设计模式
大数据新鸟10 小时前
设计模式详解——外观模式
设计模式·外观模式
缘友一世11 小时前
PentestGPT V2源码研究之工具层设计模式
设计模式
yinghuoAI202611 小时前
电商视觉进入“无人区”:萤火AI如何用三把“手术刀”重构设计 workflow
设计模式·新媒体运营·产品运营·流量运营·用户运营·内容运营·设计规范
sg_knight12 小时前
设计模式实战:观察者模式(Observer)
python·观察者模式·设计模式
Yu_Lijing14 小时前
基于C++的《Head First设计模式》笔记——MVC模式
c++·笔记·设计模式
无籽西瓜a14 小时前
【西瓜带你学设计模式 | 第十期 - 外观模式】外观模式 —— 子系统封装实现、优缺点与适用场景
java·后端·设计模式·软件工程·外观模式
han_14 小时前
JavaScript设计模式(八):命令模式实现与应用
前端·javascript·设计模式
无籽西瓜a14 小时前
【西瓜带你学设计模式 | 第九期 - 代理模式】代理模式 —— 静态与动态代理实现、优缺点与适用场景
java·后端·设计模式·软件工程·代理模式