Python设计模式——外观模式(Facade)

外观模式(Facade)

目的:外观模式用于给复杂系统提供一套简单一致的的接口,以实现某些复杂功能。
使用场景:维护一个遗留的大型系统是,可能这个系统已经非常难以维护和扩展,但是它包含很重要的功能,新的开发必须依赖于它,这样增加外观Facade类,为系统封装一个比较清晰简单的接口,让新系统与Facade对象交互,Facade与遗留代码交互所有复杂的工作。

返回 Python设计模式-outline

例子

# Complex computer parts
class CPU:
    """
    Simple CPU representation.
    """

    def freeze(self):
        print("Freezing processor.")

    def jump(self, position):
        print("Jumping to:", position)

    def execute(self):
        print("Executing.")


class Memory:
    """
    Simple memory representation.
    """

    def load(self, position, data):
        print(f"Loading from {position} data: '{data}'.")


class SolidStateDrive:
    """
    Simple solid state drive representation.
    """

    def read(self, lba, size):
        return f"Some data from sector {lba} with size {size}"


class ComputerFacade:
    """
    Represents a facade for various computer parts.
    """

    def __init__(self):
        self.cpu = CPU()
        self.memory = Memory()
        self.ssd = SolidStateDrive()

    def start(self):
        self.cpu.freeze()
        self.memory.load("0x00", self.ssd.read("100", "1024"))
        self.cpu.jump("0x00")
        self.cpu.execute()

if __name__ == '__main__':
    computer_facade = ComputerFacade()
    computer_facade.start()
    # 预期输出
    # Freezing processor.
    # Loading from 0x00 data: 'Some data from sector 100 with size 1024'.
    # Jumping to: 0x00
    # Executing.

ref

https://blog.csdn.net/ponder008/article/details/6868815

posted @   坦先生的AI资料室  阅读(123)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示