工厂模式学习笔记
什么是工厂模式?
工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。在工厂模式中,我们使用工厂方法代替直接调用构造函数来创建对象。
工厂模式的优点
- 解耦:客户端代码和具体产品代码之间解耦,客户端无需修改实例化的具体类名。
- 扩展性:添加新产品时,只需要添加相应的具体类和相应的工厂类即可,无需修改原有的代码。
- 封装性:封装了创建对象的过程,客户端不需要知道具体的实现细节。
工厂模式的缺点
- 增加了类的数量:每个具体产品都需要一个具体工厂类。
- 增加了代码的复杂度:引入了新的抽象层级,使代码变得更加复杂。
实例
假设我们有一个汽车制造工厂,它可以制造轿车、SUV和卡车。现在我们要使用工厂模式来创建这些车辆。
首先,我们需要定义一个车辆接口,它包括所有汽车共享的属性和方法。
pythonCopy Codeclass Vehicle:
def __init__(self, model, horsepower, price):
self.model = model
self.horsepower = horsepower
self.price = price
def start(self):
pass
def stop(self):
pass
然后我们定义三个具体车型:轿车、SUV和卡车。
pythonCopy Codeclass Car(Vehicle):
def __init__(self, model, horsepower, price, doors):
super().__init__(model, horsepower, price)
self.doors = doors
def start(self):
print("Starting car")
def stop(self):
print("Stopping car")
class SUV(Vehicle):
def __init__(self, model, horsepower, price, seats):
super().__init__(model, horsepower, price)
self.seats = seats
def start(self):
print("Starting SUV")
def stop(self):
print("Stopping SUV")
class Truck(Vehicle):
def __init__(self, model, horsepower, price, capacity):
super().__init__(model, horsepower, price)
self.capacity = capacity
def start(self):
print("Starting truck")
def stop(self):
print("Stopping truck")
最后,我们定义一个工厂类,该工厂类可以根据输入的参数来创建相应的汽车对象。
pythonCopy Codeclass VehicleFactory:
@staticmethod
def create_vehicle(vehicle_type, model, horsepower, price, **kwargs):
if vehicle_type == "car":
return Car(model, horsepower, price, **kwargs)
elif vehicle_type == "suv":
return SUV(model, horsepower, price, **kwargs)
elif vehicle_type == "truck":
return Truck(model, horsepower, price, **kwargs)
else:
raise ValueError("Invalid vehicle type")
使用工厂模式创建对象的示例代码如下:
pythonCopy Codecar = VehicleFactory.create_vehicle("car", "Civic", 200, 20000, doors=4)
suv = VehicleFactory.create_vehicle("suv", "Pilot", 300, 40000, seats=7)
truck = VehicleFactory.create_vehicle("truck", "F-150", 400, 50000, capacity=1000)
car.start()
suv.start()
truck.start()
输出:
Copy CodeStarting car
Starting SUV
Starting truck
以上就是一个基本的工厂模式的示例。我们可以根据需要添加新的车型,并在工厂类中添加相应的逻辑来生产它们。