前言
外观模式属于结构型模式;
外观模式:外观类通过组合给各个子系统类的对象,简化各个子系统复杂度。
一、外观模式
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()
参考