写出装饰着模式中咖啡店的具体代码
时间: 2024-05-12 12:17:07 浏览: 5
好的,下面是装饰者模式中咖啡店的具体代码:
首先定义咖啡基类,包含价格和描述信息:
```python
class Coffee:
def __init__(self):
self.description = "Unknown Coffee"
def get_description(self):
return self.description
def cost(self):
return 0.0
```
然后定义具体的咖啡种类,继承自咖啡基类:
```python
class Espresso(Coffee):
def __init__(self):
super().__init__()
self.description = "Espresso"
def cost(self):
return 1.99
class HouseBlend(Coffee):
def __init__(self):
super().__init__()
self.description = "House Blend Coffee"
def cost(self):
return 0.89
```
接下来定义装饰者基类,继承自咖啡基类:
```python
class CondimentDecorator(Coffee):
def get_description(self):
pass
```
最后定义各种装饰者,继承自装饰者基类,包含具体的描述信息和价格:
```python
class Milk(CondimentDecorator):
def __init__(self, coffee):
self.coffee = coffee
def get_description(self):
return self.coffee.get_description() + ", with milk"
def cost(self):
return self.coffee.cost() + 0.10
class Mocha(CondimentDecorator):
def __init__(self, coffee):
self.coffee = coffee
def get_description(self):
return self.coffee.get_description() + ", with mocha"
def cost(self):
return self.coffee.cost() + 0.20
```
这样就可以通过不同的装饰者来装饰不同的咖啡,如下所示:
```python
myCoffee = Espresso()
myCoffee = Milk(myCoffee)
myCoffee = Mocha(myCoffee)
print(myCoffee.get_description(), "\nTotal Cost: ", myCoffee.cost())
```
输出结果:
```
Espresso, with milk, with mocha
Total Cost: 2.29
```