工厂方法模式(Factory Method
Pattern)是一种创建型设计模式,它定义了一个用于创建对象的接口,但将实际的实例化延迟到子类。这意味着,你不再直接使用
new
关键字来创建对象,而是通过调用一个“工厂方法”来获取对象,这个工厂方法由子类实现,决定了要实例化哪个具体类。
为什么要用工厂方法模式?
在软件开发中,我们经常需要根据不同的条件创建不同类型的对象。如果直接在代码中通过
new
关键字来创建对象,会导致代码与具体的类紧密耦合。当需要添加新的产品类型或者修改现有产品类型时,就需要修改大量的客户端代码,这违反了“开闭原则”(Open-Closed
Principle),即对扩展开放,对修改关闭。
from concrete_creator import SedanCarFactory, SUVCarFactory, SportsCarFactory
defclient_code(factory): """ 客户端代码与抽象工厂接口一起工作。 """ car = factory.create_car() print(f"Client: I'm using the factory to get a car.") print(f"Client: {car.get_info()}") print(f"Client: {car.drive()}") print("-" * 30)
if __name__ == "__main__": print("App: Launched with the SedanCarFactory.") client_code(SedanCarFactory())
print("App: Launched with the SUVCarFactory.") client_code(SUVCarFactory())
print("App: Launched with the SportsCarFactory.") client_code(SportsCarFactory())
运行结果
当你运行 client.py 文件时,你会看到如下输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
App: Launched with the SedanCarFactory. Client: I'm using the factory to get a car. Client: Type: Sedan, Features: Comfortable ride, good for city. Client: Driving a comfortable Sedan car. ------------------------------ App: Launched with the SUVCarFactory. Client: I'm using the factory to get a car. Client: Type: SUV, Features: Off-road capabilities, spacious. Client: Driving a rugged SUV car. ------------------------------ App: Launched with the SportsCarFactory. Client: I'm using the factory to get a car. Client: Type: Sports Car, Features: High speed, sleek design. Client: Driving a fast Sports car. ------------------------------