开发手册 欢迎您!
软件开发者资料库

Python设计模式 - 装饰器

Python设计模式装饰器 - 从简单和简单的步骤学习Python设计模式从基本到高级概念,包括简介,Python的Gist,模型视图控制器,单例,工厂,构建器,原型,外观,命令,适配器,装饰器,代理,责任链,观察员,状态,战略,模板,飞重,抽象工厂,面向对象的模式,面向对象的概念实施,迭代器模式,词典,列表数据结构,集,队列,字符串和序列化,Python中的并发,反模式, 异常处理。

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

此模式创建一个装饰器类,它包装原始类并提供保持类的其他功能方法签名完整.

装饰器模式的动机是动态附加对象的附加职责.

如何实现装饰器设计模式

下面提到的代码是如何在Python中实现装饰器设计模式的简单演示.插图包括以课堂形式演示咖啡店.创建的咖啡类是抽象的,这意味着它无法实例化.

import sixfrom 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'

咖啡店抽象类的实现是通过下面提到的单独文件来完成的;

import coffeeshopmyCoffee = 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()))

输出

以上程序生成以下输出 :

装饰模式