裝飾模式:動態給一個對象添加一些額外的職責。
# python 3.7.6
from abc import ABCMeta, abstractmethod
class DecorateObject(metaclass=ABCMeta):
def __init__(self):
pass
@abstractmethod
def show(self):
pass
class Person(DecorateObject):
def __init__(self, name):
print("Person __init__")
self.name = name
def show(self):
print("Decorated {0}".format(self.name))
class Cat(DecorateObject):
def __init__(self, name):
print("Person __init__")
self.name = name
def show(self):
print("Decorated {0}".format(self.name))
class Finery(DecorateObject):
def __init__(self):
print("Finery __init__")
self.component = None
def decorate(self, component):
self.component = component
def show(self):
if self.component:
self.component.show()
class TShirts(Finery):
def show(self):
print(self.__class__.__name__)
super().show()
class Coat(Finery):
def show(self):
print(self.__class__.__name__)
super().show()
class Shoes(Finery):
def show(self):
print(self.__class__.__name__)
super().show()
if __name__ == "__main__":
person = Person("LiMing")
t_shirt = TShirts()
coat = Coat()
shoes = Shoes()
t_shirt.decorate(person)
coat.decorate(t_shirt)
shoes.decorate(coat)
shoes.show()