实现装饰器模式示例,添加相关类和方法,增强代码可读性
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
实例
|
||||
汤宝宝家有一台咖啡机,他会自动给美式咖啡加奶和糖...
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class Drink(ABC):
|
||||
price: float
|
||||
name: str
|
||||
|
||||
@abstractmethod
|
||||
def cost(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class Coffee(Drink):
|
||||
def __init__(self, name: str, price: float) -> None:
|
||||
self.name = name
|
||||
self.price = price
|
||||
|
||||
def cost(self) -> None:
|
||||
print(f"一杯{self.name}咖啡,价格{self.price:.2f}元")
|
||||
|
||||
|
||||
class Maker:
|
||||
def __init__(self, drink: Drink, milk_price: float, sugar_price: float) -> None:
|
||||
self.drink = drink
|
||||
self.milk_price = milk_price
|
||||
self.sugar_price = sugar_price
|
||||
|
||||
def cost(self) -> None:
|
||||
self.drink.cost()
|
||||
print(
|
||||
f"加了奶和糖,总价{self.drink.price + self.milk_price + self.sugar_price:.2f}元。"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("============= 装饰器模式 =============")
|
||||
print("自己泡杯咖啡")
|
||||
coffee = Coffee("美式", 10.0)
|
||||
coffee.cost()
|
||||
print("\n用咖啡机泡杯咖啡")
|
||||
new_coffee = Maker(coffee, milk_price=1.0, sugar_price=1.0)
|
||||
new_coffee.cost()
|
||||
print("\n=========== 装饰器模式结束 ===========")
|
||||
Reference in New Issue
Block a user