请给出一个交通工具python工厂模式示例
时间: 2024-05-08 08:20:32 浏览: 9
好的,以下是一个交通工具 Python 工厂模式的示例:
```python
class Transport:
def drive(self):
pass
class Car(Transport):
def drive(self):
print("Driving a car.")
class Bus(Transport):
def drive(self):
print("Driving a bus.")
class Bike(Transport):
def drive(self):
print("Riding a bike.")
class TransportFactory:
@staticmethod
def create_transport(transport_type):
if transport_type == "car":
return Car()
elif transport_type == "bus":
return Bus()
elif transport_type == "bike":
return Bike()
else:
raise ValueError("Invalid transport type.")
# Example usage
car = TransportFactory.create_transport("car")
car.drive() # Driving a car.
bus = TransportFactory.create_transport("bus")
bus.drive() # Driving a bus.
bike = TransportFactory.create_transport("bike")
bike.drive() # Riding a bike.
```
在这个示例中,我们定义了一个 `Transport` 基类,以及三个子类 `Car`、`Bus` 和 `Bike`,它们都重写了 `drive` 方法。我们还定义了一个工厂类 `TransportFactory`,它有一个静态方法 `create_transport`,它接受一个字符串参数 `transport_type`,并返回一个相应的子类实例。最后,我们使用 `TransportFactory` 来创建并使用不同类型的交通工具对象。