结构型模式 - 外观模式 (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();
    }
}
相关推荐
开心香辣派小星6 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式
阿杰同学15 小时前
Java 设计模式 面试题及答案整理,最新面试题
java·开发语言·设计模式
xunyan623416 小时前
面向对象(下)-模版方法的设计模式其应用场景
java·学习·设计模式
此剑之势丶愈斩愈烈17 小时前
设计模式学习
学习·设计模式
雨中飘荡的记忆19 小时前
设计模式之命令模式详解
设计模式·命令模式
小生不才yz19 小时前
设计模式 - 命令模式
设计模式·命令模式
雨中飘荡的记忆19 小时前
设计模式之门面模式详解
microsoft·设计模式
明洞日记19 小时前
【设计模式手册016】中介者模式 - 解耦多对象交互
c++·设计模式·交互·中介者模式
开心香辣派小星20 小时前
23种设计模式-19策略模式(Strategy Pattern)
java·设计模式·策略模式
咨询QQ688238861 天前
ACO蚁群算法优化KELM核极限学习机(ACO-KELM)回归预测MATLAB代码 代码注释清...
外观模式