python版本的装饰器模式

# -*- coding:UTF-8 -*-
import abc


class Component(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def operation(self):
        pass


class ConcreteComponent(Component):
    def operation(self):
        print("具体对象的操作")


class Decorator(Component):

    def set_component(self, component):
        self._component = component

    def operation(self):
        if hasattr(self, '_component'):
            self._component.operation()


class ConcreteDecoratorA(Decorator):
    def __init__(self):
        self.__added_state = ''

    def operation(self):
        super().operation()
        self.__added_state = "new state"
        print("具体装饰对象A的操作")


class ConcreteDecoratorB(Decorator):

    def operation(self):
        super().operation()
        self.__added_behavior()
        print("具体装饰对象B的操作")

    def __added_behavior(self):
        print('Add other behavior')


if __name__ == "__main__":
    c=ConcreteComponent()
    d1=ConcreteDecoratorA()
    d2=ConcreteDecoratorB()
    d1.set_component(c)
    d2.set_component(d1)
    d2.operation()

 

posted @ 2018-01-25 15:08  gjw  阅读(113)  评论(0)    收藏  举报