使用装饰器模式和桥接模式实现大中小尺寸的咖啡和调料尺寸的功能
时间: 2023-08-09 16:10:12 浏览: 67
装饰模式小应用
首先,我们需要定义咖啡和调料的抽象类:
```python
from abc import ABC, abstractmethod
class Beverage(ABC):
@abstractmethod
def cost(self):
pass
@abstractmethod
def get_description(self):
pass
class CondimentDecorator(Beverage):
@abstractmethod
def cost(self):
pass
@abstractmethod
def get_description(self):
pass
```
接下来,我们定义具体的咖啡类:
```python
class Espresso(Beverage):
def cost(self):
return 1.99
def get_description(self):
return "Espresso"
```
```python
class DarkRoast(Beverage):
def cost(self):
return 0.99
def get_description(self):
return "Dark Roast Coffee"
```
```python
class Decaf(Beverage):
def cost(self):
return 1.05
def get_description(self):
return "Decaf Coffee"
```
然后,我们定义具体的调料类:
```python
class Milk(CondimentDecorator):
def __init__(self, beverage):
self.beverage = beverage
def cost(self):
return self.beverage.cost() + 0.10
def get_description(self):
return self.beverage.get_description() + ", Milk"
```
```python
class Mocha(CondimentDecorator):
def __init__(self, beverage):
self.beverage = beverage
def cost(self):
return self.beverage.cost() + 0.20
def get_description(self):
return self.beverage.get_description() + ", Mocha"
```
```python
class Soy(CondimentDecorator):
def __init__(self, beverage):
self.beverage = beverage
def cost(self):
return self.beverage.cost() + 0.15
def get_description(self):
return self.beverage.get_description() + ", Soy"
```
最后,我们可以使用装饰器模式和桥接模式来实现大中小尺寸的咖啡和调料尺寸的功能:
```python
class Size:
def cost(self):
pass
def get_description(self):
pass
class Small(Size):
def __init__(self, beverage):
self.beverage = beverage
def cost(self):
return self.beverage.cost() - 0.10
def get_description(self):
return self.beverage.get_description() + ", Small"
class Medium(Size):
def __init__(self, beverage):
self.beverage = beverage
def cost(self):
return self.beverage.cost()
def get_description(self):
return self.beverage.get_description() + ", Medium"
class Large(Size):
def __init__(self, beverage):
self.beverage = beverage
def cost(self):
return self.beverage.cost() + 0.10
def get_description(self):
return self.beverage.get_description() + ", Large"
beverage = Espresso()
beverage = Milk(beverage)
beverage = Mocha(beverage)
beverage = Large(beverage)
print(beverage.get_description(), "$" + str(beverage.cost()))
```
输出结果为:
```
Espresso, Milk, Mocha, Large $2.39
```
这里我们定义了一个 `Size` 基类和三个子类 `Small`、`Medium`、`Large`,用于实现不同尺寸的咖啡。在具体的咖啡和调料类中,我们使用了桥接模式,将 `Beverage` 和 `CondimentDecorator` 作为参数传递给具体的调料类,实现了装饰器模式。最后,在客户端代码中,我们可以通过组合不同的咖啡和调料对象,来实现各种不同口味和尺寸的咖啡,并且可以根据需要随时添加或删除调料对象,非常灵活方便。
阅读全文