装饰模式
发布时间:2020-12-14 04:25:13 所属栏目:大数据 来源:网络整理
导读:模式定义:动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活。 模式结构: Component: 抽象构件 ConcreteComponent: 具体构件 Decorator: 抽象装饰类 ConcreteDecorator: 具体装饰类 ? 应用场景:
|
模式定义:动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活。 模式结构:
?
应用场景: ? 场景介绍:变形金刚本体为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()
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

