裝飾器模式允許用戶(hù)在不改變其結(jié)構(gòu)的情況下向現(xiàn)有對(duì)象添加新功能。 這種類(lèi)型的設(shè)計(jì)模式屬于結(jié)構(gòu)模式,因?yàn)榇四J匠洚?dāng)現(xiàn)有類(lèi)的包裝。
這個(gè)模式創(chuàng)建了一個(gè)裝飾器類(lèi),它封裝了原始類(lèi),并提供了額外的功能,保持了類(lèi)方法簽名的完整性。
裝飾者模式的動(dòng)機(jī)是動(dòng)態(tài)地附加對(duì)象的額外職責(zé)(功能)。
下面提到的代碼是如何在Python中實(shí)現(xiàn)裝飾器設(shè)計(jì)模式的簡(jiǎn)單演示。 該示例涉及以類(lèi)形式展示咖啡店(coffeeshop
類(lèi))。 創(chuàng)建的 coffee
類(lèi)是一個(gè)抽象類(lèi),這意味著它不能被實(shí)例化。
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
抽象類(lèi)的實(shí)現(xiàn)是通過(guò)一個(gè)單獨(dú)的文件完成的 -
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()))
執(zhí)行上述程序生成以下輸出 -