大话设计模式之Python实现【装饰模式】

原创
2015/07/19 14:09
阅读数 149
# coding=utf8

__author__ = 'smilezjw'


class Person(object):
    def __init__(self, name):
        self.name = name

    def show(self):
        print 'Dressed %s' % self.name


class Finery(Person):
    component = None

    def __init__(self):
        pass

    def decorate(self, component):
        self.component = component

    def show(self):
        if self.component is not None:
            self.component.show()


class TShirts(Finery):
    def __init__(self):
        pass

    def show(self):
        print 'Big Tshirts'
        super(TShirts, self).show()


class BigTrouser(Finery):
    def __init__(self):
        pass

    def show(self):
        print 'Big Trouser'
        super(BigTrouser, self).show()

if __name__ == '__main__':
    wen = Person('Wen')
    ts = TShirts()        # self.component = None
    bt = BigTrouser()     # self.component = None
    ts.decorate(wen)      # self.component = wen
    bt.decorate(ts)       # self.component = ts
    bt.show()             # self.component = ts

模式特点:把每个要装饰的功能放在单独的类中,用这个类去包装所要装饰的对象,因此客户端可以有选择地、按顺序的使用装饰功能包装对象。


展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部