果园种植有苹果、梨子、桃子和葡萄等水果,根据订货向商店供货。现在,商店就是客户端,水果是产品,使用简单工厂模式来实现果园向商店提供一定数量的某种水果。
时间: 2024-05-03 08:21:51 浏览: 27
首先,我们需要定义一个水果类,它包含水果的属性和方法:
```python
class Fruit:
def __init__(self, name, price):
self.name = name
self.price = price
def get_name(self):
return self.name
def get_price(self):
return self.price
def set_price(self, price):
self.price = price
```
接下来,我们需要定义一个工厂类,根据客户端的需求来生产不同种类的水果:
```python
class FruitFactory:
def create_fruit(self, fruit_type, quantity):
if fruit_type == "apple":
return Apple(quantity)
elif fruit_type == "pear":
return Pear(quantity)
elif fruit_type == "peach":
return Peach(quantity)
elif fruit_type == "grape":
return Grape(quantity)
else:
raise ValueError("Invalid fruit type")
```
在工厂类中,我们根据客户端传入的水果类型来创建相应的水果对象。每个水果类都继承自水果类,并实现了自己的价格和数量属性。
```python
class Apple(Fruit):
def __init__(self, quantity):
super().__init__("apple", 5)
self.quantity = quantity
def get_total_price(self):
return self.price * self.quantity
class Pear(Fruit):
def __init__(self, quantity):
super().__init__("pear", 4)
self.quantity = quantity
def get_total_price(self):
return self.price * self.quantity
class Peach(Fruit):
def __init__(self, quantity):
super().__init__("peach", 6)
self.quantity = quantity
def get_total_price(self):
return self.price * self.quantity
class Grape(Fruit):
def __init__(self, quantity):
super().__init__("grape", 10)
self.quantity = quantity
def get_total_price(self):
return self.price * self.quantity
```
最后,我们可以使用工厂类来创建指定种类和数量的水果,然后向商店提供供货。
```python
factory = FruitFactory()
apple = factory.create_fruit("apple", 100)
print("供应商提供了 {} 个 {},总价为 {} 元。".format(apple.quantity, apple.get_name(), apple.get_total_price()))
pear = factory.create_fruit("pear", 50)
print("供应商提供了 {} 个 {},总价为 {} 元。".format(pear.quantity, pear.get_name(), pear.get_total_price()))
peach = factory.create_fruit("peach", 80)
print("供应商提供了 {} 个 {},总价为 {} 元。".format(peach.quantity, peach.get_name(), peach.get_total_price()))
grape = factory.create_fruit("grape", 200)
print("供应商提供了 {} 个 {},总价为 {} 元。".format(grape.quantity, grape.get_name(), grape.get_total_price()))
```
输出结果:
```
供应商提供了 100 个 apple,总价为 500 元。
供应商提供了 50 个 pear,总价为 200 元。
供应商提供了 80 个 peach,总价为 480 元。
供应商提供了 200 个 grape,总价为 2000 元。
```
通过简单工厂模式,我们可以很方便地创建不同种类和数量的水果,并向客户端提供供货。