装饰器模式包含以下主要角色:
1. 组件(Component): 定义一个对象接口,可以动态地给这些对象添加职责。
2. 具体组件(ConcreteComponent): 实现了组件接口的具体类,是被装饰的对象。
3. 装饰器(Decorator): 持有一个指向组件对象的引用,并实现了组件接口。装饰器可以有多个层次,每个层次可以为组件对象添加新的功能。
4. 具体装饰器(ConcreteDecorator): 扩展了装饰器接口,实现了具体的装饰逻辑。
下面是一个简单的装饰器模式的例子,假设我们有一个咖啡类,我们想通过装饰器为咖啡添加不同的调料:
# 组件接口
class Coffee:
def cost(self):
pass
# 具体组件:普通咖啡
class SimpleCoffee(Coffee):
def cost(self):
return 5
# 装饰器
class CoffeeDecorator(Coffee):
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost()
# 具体装饰器:加糖
class SugarDecorator(CoffeeDecorator):
def cost(self):
return self._coffee.cost() + 2
# 具体装饰器:加牛奶
class MilkDecorator(CoffeeDecorator):
def cost(self):
return self._coffee.cost() + 3
# 客户端代码
if __name__ == "__main__":
# 创建具体组件对象
simple_coffee = SimpleCoffee()
# 创建具体装饰器对象并包装组件对象
sugar_coffee = SugarDecorator(simple_coffee)
milk_sugar_coffee = MilkDecorator(sugar_coffee)
# 输出咖啡的成本
print("Cost of Simple Coffee:", simple_coffee.cost())
print("Cost of Coffee with Sugar:", sugar_coffee.cost())
print("Cost of Coffee with Milk and Sugar:", milk_sugar_coffee.cost())
在上述示例中,Coffee 是组件接口,SimpleCoffee 是具体组件。CoffeeDecorator 是装饰器,它包含一个指向组件对象的引用,并实现了组件接口。SugarDecorator 和 MilkDecorator 是具体装饰器,它们分别在咖啡中加糖和加牛奶的成本。
客户端代码可以通过组合不同的装饰器来创建具有不同调料的咖啡,而无需修改原始咖啡类的代码。
装饰器模式的优点在于它允许动态地为对象添加新的功能,同时保持了原始对象的简单性。这种模式使得代码更加灵活、可扩展,并符合开放/封闭原则。
转载请注明出处:http://www.zyzy.cn/article/detail/11847/设计模式