随笔 - 241  文章 - 1  评论 - 58  阅读 - 85万 

前言

外观模式属于结构型模式;

外观模式:外观类通过组合给各个子系统类的对象,简化各个子系统复杂度。

一、外观模式

1.概念

为子系统中的一组接口提供1个一致的界面。

外观模式定义了1个高层接口,这个高层接口使得这1子系统更加容易使用;

2.角色

外观(Facade)

子系统类(Subsystem Classes)

3.优点

减少系统直接相互依赖(解耦)

提高灵活性

提高安全性

4.代码

复制代码
from abc import ABC, abstractmethod


# 子系统类1
class CPU():
    def run(self):
        print("CPU开始运行")

    def stop(self):
        print("CPU停止运行")


# 子系统类2
class Disk():
    def run(self):
        print("硬盘开始运行")

    def stop(self):
        print("硬盘停止运行")


# 子系统类3
class Memory():
    def run(self):
        print("内存通电")

    def stop(self):
        print("内存断电")


# 外观(Facade):组合各个子系统类的对象
class Computer():
    def __init__(self):
        self.cpu = CPU()
        self.disk = Disk()
        self.memory = Memory()

    def run(self):
        self.cpu.run()
        self.disk.run()
        self.memory.run()

    def stop(self):
        self.cpu.stop()
        self.disk.stop()
        self.memory.stop()


# 客户端
if __name__ == '__main__':
    c = Computer()
    c.run()
    c.stop()
复制代码

 

 

参考

posted on   Martin8866  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示