装饰模式
模式定义:动态地给一个对象增加一些额外的职责(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()

浙公网安备 33010602011771号