随笔 - 258  文章 - 0  评论 - 0  阅读 - 32125

外观模式

定义: 隐藏了系统的复杂性,并向客户端提供了一个可以访问系统的接口。

举例(每个Computer都有CPU、Memory、Disk。在Computer开启和关闭的时候,相应的部件也会开启和关闭),类图如下:

 

 

首先是子系统类:

复制代码
public class CPU {
 
    public void start() {
        System.out.println("cpu is start...");
    }
 
    public void shutDown() {
        System.out.println("CPU is shutDown...");
    }
}
 
public class Disk {
    public void start() {
        System.out.println("Disk is start...");
    }
 
    public void shutDown() {
        System.out.println("Disk is shutDown...");
    }
}
 
public class Memory {
    public void start() {
        System.out.println("Memory is start...");
    }
 
    public void shutDown() {
        System.out.println("Memory is shutDown...");
    }
}
复制代码

然后是,门面类Facade

复制代码
public class Computer {
 
    private CPU cpu;
    private Memory memory;
    private Disk disk;
 
    public Computer() {
        cpu = new CPU();
        memory = new Memory();
        disk = new Disk();
    }
 
    public void start() {
        System.out.println("Computer start begin");
        cpu.start();
        disk.start();
        memory.start();
        System.out.println("Computer start end");
    }
 
    public void shutDown() {
        System.out.println("Computer shutDown begin");
        cpu.shutDown();
        disk.shutDown();
        memory.shutDown();
        System.out.println("Computer shutDown end...");
    }
}
复制代码

最后为,客户角色

复制代码
public class Client {
 
    public static void main(String[] args) {
        Computer computer = new Computer();
        computer.start();
        System.out.println("=================");
        computer.shutDown();
    }
 
}
复制代码

优点
  - 松散耦合

  使得客户端和子系统之间解耦,让子系统内部的模块功能更容易扩展和维护;

  - 简单易用

  客户端根本不需要知道子系统内部的实现,或者根本不需要知道子系统内部的构成,它只需要跟Facade类交互即可。

  - 更好的划分访问层次

 有些方法是对系统外的,有些方法是系统内部相互交互的使用的。子系统把那些暴露给外部的功能集中到门面中,这样就可以实现客户端的使用,很好的隐藏了子系统内部的细节。

posted on   季昂  阅读(46)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· 《HelloGitHub》第 108 期
· MQ 如何保证数据一致性?
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
历史上的今天:
2020-10-19 Python 基础学习
< 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

点击右上角即可分享
微信分享提示