装饰器模式

装饰器模式动态将责任附加到对象上。想要扩展功能,装饰者提供有别于继承的另一种选择。

装饰器模式的特点:

  1. 继承属于扩展形式之一,但不见得是达到弹性设计的最佳方式
  2. 在我们的设计中,应该允许行为被扩展,而不用修改现有的代码
  3. 组合和委托可用在运行时动态的加上新的行为
  4. 除了继承,装饰者模式也可以让我们扩展行为
  5. 装饰者模式会导致出现很多小的对象,过度使用,会让程序变的很复杂
  6. 可以用很很多个装饰者包装一个组件
  7. 装饰者可以在被装饰者的前面/后面加上自己的行为,甚至将被装饰者的行为整个取代掉,来达到某种目的
  8. 装饰者模式意味着一群装饰者类,这些类可以用来包装具体的组件
  9. 装饰者类反映出被装饰者的类型,事实上他们具有相同的类型,都是通过继承或者接口实现
    10.装饰者一般对组件的客户是透明的,除非客户依赖于组件的特殊类型

python实现装饰器模式:

"""
装饰器模式
"""


class Beverages(object):
    """
    饮料
    """
    description = ''

    def get_description(self):
        return self.description

    def cost(self):
        raise NotImplementedError()


class Condiment(Beverages):
    """
    调味料
    """

    def get_description(self):
        return self.description


class Espresso(Beverages):
    description = "Espresso"

    def cost(self):
        return 1.99


class HouseBlend(Beverages):
    """
    家庭混合
    """
    description = "HouseBlend"

    def cost(self):
        return 0.89


class Mocha(Condiment):
    description = "Mocha"

    def __init__(self, beverage):
        self.beverage = beverage

    def get_description(self):
        return self.description + " " + self.beverage.get_description()

    def cost(self):
        return 0.2 + self.beverage.cost()


if __name__ == "__main__":
    house_blent = HouseBlend()
    mocha_house_blend = Mocha(house_blent)
    cost = mocha_house_blend.cost()
    print(mocha_house_blend.get_description() + "  cost: %s" % cost)

    espresso = Espresso()
    mocha_espress = Mocha(espresso)
    cost = mocha_espress.cost()
    print(mocha_espress.get_description() + ' cost: %s ' % cost)

备注:
博客中有关设计模式的例子都是《head first 设计模式》中的例子,只不过是用python实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值