設計模式之三--裝飾模式

裝飾模式:動態給一個對象添加一些額外的職責。

# 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()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章