结构型模式 - 外观模式 (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();
    }
}
相关推荐
消失的旧时光-19438 小时前
kmp需要技能
android·设计模式·kotlin
JohnYan13 小时前
安全密钥(Security Key)和认证技术相关词汇表
后端·安全·设计模式
yinghuaqipao17 小时前
面向对象——设计模式(创建型)
android·java·设计模式
WaWaJie_Ngen17 小时前
【设计模式】代理模式(Proxy)
设计模式·代理模式
麦麦鸡腿堡17 小时前
Java的抽象类实践-模板设计模式
java·开发语言·设计模式
WaWaJie_Ngen17 小时前
【设计模式】外观模式/门面模式(Facaed)
设计模式·外观模式
Asort17 小时前
JavaScript设计模式(十九)——观察者模式 (Observer)
前端·javascript·设计模式
围巾哥萧尘18 小时前
英语老师的秘密武器:Trae智能体写作批改智能体 (改作文一条龙)🧣
设计模式
Miku1618 小时前
吴恩达Agentic AI课程Module1学习笔记
人工智能·设计模式·agent
我的xiaodoujiao20 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
python·学习·测试工具·设计模式·pytest