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 @ 2022-07-26 17:44  坦先生的AI资料室  阅读(116)  评论(0编辑  收藏  举报