当前位置:首页>文章>设计模式>外观模式详解|设计模式学习指南

外观模式详解|设计模式学习指南

外观模式详解

1️⃣ 概念

定义: 又叫门面模式,提供了一个统一的接口,用来访问子系统中的一群接口;外观模式定义了一个高层接口,让子系统更容易使用。
类型: 结构性

2️⃣ 适用场景

  • 当子系统越来越复杂,增加外观模式提供简单调用接口
  • 构建多层系统结构,利用外观对象作为每层的入口,简化层间调用

3️⃣ 优点

  • 简化了调用过程,无需深入了解子系统,防止带来风险
  • 减少系统依赖,松散耦合
  • 更好的划分访问的层次
  • 符合迪米特法则即最少知道原则

4️⃣ 缺点

  • 增加子系统扩展子系统行为容易引入风险
  • 不符合开闭原则(在增加子系统扩展子系统时)

5️⃣ 外观模式相关的设计模式

  • 外观模式和中介者模式: 外观模式关注的是外界与子系统之间的交互,中介者模式关注的是内部各子系统之间的交互
  • 外观模式和单例模式: 通常情况下我们可以将外观模式的外观对象做成单例的来使用
  • 外观模式和抽象工厂模式: 外观类可以通过抽象工厂获取子系统的实例,这样的话子系统就可以利用抽象工厂对外观类屏蔽内部实现

6️⃣ 外观模式编码实现

① 创建CPU类

class CPU:
    def open(self):
        print("open cpu")

    def close(self):
        print("close cpu")

② 创建硬盘Disk类

class Disk:
    def open(self):
        print("open disk")

    def close(self):
        print("close disk")

③ 创建Computer类

class Computer:
    def __init__(self):
        self.cpu = CPU()
        self.disk = Disk()

    def open(self):
        self.cpu.open()
        self.disk.open()

    def close(self):
        self.cpu.close()
        self.disk.close()

④ 创建测试代码

def main():
    computer = Computer()
    computer.open()
    print("玩一会电脑")
    computer.close()

if __name__ == "__main__":
    main()

8️⃣ 外观模式的实际应用

外观模式在Django框架中大量使用,比如Django的ORM就是数据库操作的外观模式实现,有兴趣的小伙伴可以查看Django源码。

设计模式

原型模式详解 | 深入理解 Prototype Pattern 的实现与应用

2025-9-4 17:18:41

设计模式

装饰者模式详解(Python版)| 设计模式教程

2025-9-6 15:37:50

搜索