python装饰器设计方法_装饰器设计模式

本篇文章帮大家学习装饰器设计模式,包含了装饰器设计模式使用方法、操作技巧、实例演示和注意事项,有一定的学习价值,大家可以用来参考。

装饰器模式允许用户在不改变其结构的情况下向现有对象添加新功能。 这种类型的设计模式属于结构模式,因为此模式充当现有类的包装。

这个模式创建了一个装饰器类,它封装了原始类,并提供了额外的功能,保持了类方法签名的完整性。

装饰者模式的动机是动态地附加对象的额外职责(功能)。

如何实现装饰设计模式?

下面提到的代码是如何在python中实现装饰器设计模式的简单演示。 该示例涉及以类形式展示咖啡店(coffeeshop类)。 创建的 coffee 类是一个抽象类,这意味着它不能被实例化。

import six

from abc import ABCMeta

@six.add_metaclass(ABCMeta)

class Abstract_Coffee(object):

def get_cost(self):

pass

def get_ingredients(self):

pass

def get_tax(self):

return 0.1*self.get_cost()

class Concrete_Coffee(Abstract_Coffee):

def get_cost(self):

return 1.00

def get_ingredients(self):

return 'coffee'

@six.add_metaclass(ABCMeta)

class Abstract_Coffee_Decorator(Abstract_Coffee):

def __init__(self,decorated_coffee):

self.decorated_coffee = decorated_coffee

def get_cost(self):

return self.decorated_coffee.get_cost()

def get_ingredients(self):

return self.decorated_coffee.get_ingredients()

class Sugar(Abstract_Coffee_Decorator):

def __init__(self,decorated_coffee):

Abstract_Coffee_Decorator.__init__(self,decorated_coffee)

def get_cost(self):

return self.decorated_coffee.get_cost()

def get_ingredients(self):

return self.decorated_coffee.get_ingredients() + ', sugar'

class Milk(Abstract_Coffee_Decorator):

def __init__(self,decorated_coffee):

Abstract_Coffee_Decorator.__init__(self,decorated_coffee)

def get_cost(self):

return self.decorated_coffee.get_cost() + 0.25

def get_ingredients(self):

return self.decorated_coffee.get_ingredients() + ', milk'

class Vanilla(Abstract_Coffee_Decorator):

def __init__(self,decorated_coffee):

Abstract_Coffee_Decorator.__init__(self,decorated_coffee)

def get_cost(self):

return self.decorated_coffee.get_cost() + 0.75

def get_ingredients(self):

return self.decorated_coffee.get_ingredients() + ', vanilla'

如下所述,coffeeshop抽象类的实现是通过一个单独的文件完成的 -

import coffeeshop

myCoffee = coffeeshop.Concrete_Coffee()

print('Ingredients: '+myCoffee.get_ingredients()+

'; Cost: '+str(myCoffee.get_cost())+'; sales tax = '+str(myCoffee.get_tax()))

myCoffee = coffeeshop.Milk(myCoffee)

print('Ingredients: '+myCoffee.get_ingredients()+

'; Cost: '+str(myCoffee.get_cost())+'; sales tax = '+str(myCoffee.get_tax()))

myCoffee = coffeeshop.Vanilla(myCoffee)

print('Ingredients: '+myCoffee.get_ingredients()+

'; Cost: '+str(myCoffee.get_cost())+'; sales tax = '+str(myCoffee.get_tax()))

myCoffee = coffeeshop.Sugar(myCoffee)

print('Ingredients: '+myCoffee.get_ingredients()+

'; Cost: '+str(myCoffee.get_cost())+'; sales tax = '+str(myCoffee.get_tax()))

执行上述程序生成以下输出 -

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值