
装饰器模式是一种结构型设计模式,旨在动态的给一个对象添加额外的职责。
不改变原有对象结构的情况下,动态地给对象添加新的功能或职责,实现透明地对对象进行功能的扩展。

- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- __doc__ = """
- 装饰器模式
- 例:实现咖啡店的订单系统,不同种类的咖啡可以搭配不同的调料,使用装饰器对原有对象 增加相应配料信息和价格
- """
-
-
- class Coffee:
- """基础组件类 - 咖啡"""
-
- def cost(self):
- return 9.9
-
-
- class Espresso(Coffee):
- """具体组件类 - 浓缩咖啡"""
-
- def cost(self):
- return super().cost() + 1
-
- def description(self):
- return "浓缩咖啡"
-
-
- class Decorator(Coffee):
- """装饰器基类 - 调料"""
-
- def __init__(self, coffee):
- self._coffee = coffee
-
- def cost(self):
- return self._coffee.cost()
-
- def description(self):
- return self._coffee.description()
-
-
- class Milk(Decorator):
- """具体装饰器类 - 牛奶"""
-
- def cost(self):
- return super().cost() + 2
-
- def description(self):
- return super().description() + " + 牛奶"
-
-
- class Sugar(Decorator):
- """具体装饰器类 - 糖"""
-
- def cost(self):
- return super().cost() + 0.5
-
- def description(self):
- return super().description() + " + 糖"
-
-
- # 客户端代码
- if __name__ == "__main__":
- """
- 浓缩咖啡 (10.9 💰)
- 浓缩咖啡 + 牛奶 (12.9 💰)
- 浓缩咖啡 + 牛奶 + 糖 (13.4 💰)
- """
- coffee = Espresso()
- print(f"{coffee.description()} ({coffee.cost()} 💰)")
-
- # 加入牛奶
- coffee_with_milk = Milk(coffee)
- print(f"{coffee_with_milk.description()} ({coffee_with_milk.cost()} 💰)")
-
- # 再加入糖
- coffee_with_sugar = Sugar(coffee_with_milk)
- print(f"{coffee_with_sugar.description()} ({coffee_with_sugar.cost()} 💰)")