菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
198
0

装饰模式

原创
05/13 14:22
阅读数 66546

模式定义:动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活。

模式结构:

  • Component: 抽象构件
  • ConcreteComponent: 具体构件
  • Decorator: 抽象装饰类
  • ConcreteDecorator: 具体装饰类

 

应用场景:
1)需要扩展一个类的功能,或给一个类增加附加责任。
2)需要动态的给一个对象增加功能,这些功能可以再动态地撤销。
3)需要增加一些基本功能的排列组合而产生的非常大量的功能,从而使继承变得不现实。

 

场景介绍:变形金刚本体为car,可以变身为robot,airplane

from abc import ABCMeta, abstractmethod


class AutoBotsInterface(metaclass=ABCMeta):
    @abstractmethod
    def move(self):
        pass


class Car(AutoBotsInterface):
    def move(self):
        print("driver")


# 分割线
# 此处我们需要动态增加Car的功能,即装饰car实例
class Changer(AutoBotsInterface):
    def __init__(self, instanceObj):
        self._instance = instanceObj

    def move(self):
        self._instance.move()
        # 新增功能
        pass


class Airplane(Changer):
    def move(self):
        print("fly")


class Robot(Changer):
    def move(self):
        print("run")

    def speak(self):
        print("i can speak")


if __name__ == "__main__":
    bumblebee = Car()
    bumblebee.move()

    airplane = Airplane(bumblebee)
    robot = Robot(bumblebee)

    airplane.move()
    robot.move()
    robot.speak()

  

发表评论

0/200
198 点赞
0 评论
收藏