python装饰模式

python装饰模式,
1、抽象类与抽象方法。

一、意图:动态地给一个对象添加一些额外的职责,就增加功能来说,Decorator模式相比生成子类更为灵活。
二、适用性:
1、在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
2、处理那些可以撤消的职责。
3、当不能采用生成子类的方法进行扩充时,一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。
三、参与者
Component:定义一个对象接口,可以给这些对象动态地添加职责
ConcreteComponent: 定义一个对象,可以给这个对象添加一些职责。
Decorator:维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。
ConcreteDecorator:向组件添加职责。
四、协作
Decorator将请求转发给它的Component对象,并有可能在转发请求前后执行一些附加的动作。

#encoding=utf-8
__author__ = 'xxx'

from abc import ABCMeta, abstractmethod


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

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

    def show(self):
        print('%s开始穿衣' % self.name)
        self.component.show()


class Finery():
    def __init__(self):
        self.component = None

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

    __metaclass__ = ABCMeta #用于创建抽象基类

    @abstractmethod
    def show(self):   #子类必须实现
        # print("ddd--{}".format(self.component))
        if self.component:
            self.component.show()  #执行tshirt.show,嵌套打印
            # print("ddd")


class TShirt(Finery):
    def show(self):
        Finery.show(self)
        print('穿TShirst')


class Trouser(Finery):
    def show(self):
        Finery.show(self)
        print('穿裤子')


class Shoe(Finery):
    def show(self):
        Finery.show(self)
        print('穿鞋子')


class Tie(Finery):
    def show(self):
        Finery.show(self)
        print('穿领带')


if __name__ == '__main__':
    person = Person('kevin')
    tshirt = TShirt()
    trouser = Trouser()
    shoe = Shoe()
    tie = Tie()
    
    # tshirt.show()
    # print("#######\n")
    trouser.decorator(tshirt)
    # trouser.show()
    shoe.decorator(trouser)
    tie.decorator(shoe)
    person.decorator(tie)
    person.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值