zl程序教程

您现在的位置是:首页 >  后端

当前栏目

设计模式(Python语言)----外观模式

2023-09-14 09:12:51 时间

更多信息请参考 【设计模式】

外观模式内容

为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用

外观模式中的角色

  • 外观(facade)
  • 子系统类(subsystem classes)

外观模式的优点

  • 减少了系统的相互依赖
  • 提高了灵活性
  • 提高了安全性

外观模式实例

代码如下

from abc import ABCMeta,abstractmethod

class CPU:
    def run(self):
        print("CPU开始运行...")

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

class Disk:
    def run(self):
        print("硬盘开始工作...")

    def stop(self):
        print("硬盘停止工作...")

class Memory:
    def run(self):
        print("内存通电")

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

class Computer(object):
    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__":
    computer=Computer()
    computer.run()
    computer.stop()

执行结果如下:

CPU开始运行...
硬盘开始工作...
内存通电
CPU停止运行...
硬盘停止工作...
内存断电

推荐阅读

设计模式(Python语言)----面向对象设计SOLID原则

设计模式(Python语言)----设计模式分类

设计模式(Python语言)----简单工厂模式

设计模式(Python语言)----工厂方法模式

设计模式(Python语言)----抽象工厂模式

设计模式(Python语言)----建造者模式

设计模式(Python语言)----单例模式

设计模式(Python语言)----适配器模式

设计模式(Python语言)----桥模式

设计模式(Python语言)----组合模式

设计模式(Python语言)----外观模式

设计模式(Python语言)----代理模式

设计模式(Python语言)----责任链模式

设计模式(Python语言)----观察者模式

设计模式(Python语言)----策略模式

设计模式(Python语言)----模板方法模式