设计模式—结构型模式之外观模式(门面模式)

设计模式—结构型模式之外观模式(门面模式)

外观(Facade)模式又叫作门面模式,是一种通过为多个复杂的子系统提供一个一致的接口,而使这些子系统更加容易被访问的模式。

例子

我们的电脑会有很多 组件,比如CPU、硬盘、内存等等;如果我们电脑需要启动的话,需要挨个去调用每个组件的启动方法;停止逻辑也是一样;我们可以提取到一个组合的类中,提供一个整体的启动方法,直接调用,这就是门面模式的使用。

代码如下:

public class Cpu {
    public void start(){
        System.out.println("CPU启动了");
    }
}
public class Disk {
    public void start(){
        System.out.println("硬盘启动了");
    }
}
public class Memory {
    public void start(){
        System.out.println("内存启动了");
    }
}
/**
 * 门面类
 */
public class ComputerFaced {
    private Cpu cpu;
    private Memory memory;
    private Disk disk;

    public ComputerFaced(){
        this.cpu = new Cpu();
        this.memory = new Memory();
        this.disk = new Disk();
    }

    public void start(){
        this.cpu.start();
        this.memory.start();
        this.disk.start();
    }
}

我们的客户使用,就是如下:

public class FacedTest {
    public static void main(String[] args) {
        ComputerFaced computerFaced = new ComputerFaced();
        computerFaced.start();
    }
}

运行如下:

运行截图

posted on   随机的未知  阅读(16)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示