# 工厂方法 > 原文: [https://pythonspot.com/factory-method/](https://pythonspot.com/factory-method/) 我们可能并不总是知道我们要预先创建什么样的对象。 在用户请求执行后,只能在执行时创建 _ 的某些对象。_ 可能使用**工厂方法**的示例: * 用户可以单击创建对象的特定按钮。 * 用户可以创建几个不同类型的新文档。 * 如果用户启动 Web 浏览器,则浏览器不会事先知道将打开多少个选项卡(每个选项卡都是一个对象)。 ## 工厂方法模式 To deal with this we can use the _factory method_ pattern. The idea is to have one function, the factory, that takes an input string and outputs an object. ```py obj = Car.factory("Racecar") obj.drive() ``` **关键事实**:_ 工厂方法返回(新)对象。_ 对象的类型取决于您指定的输入字符串的类型。 这种技术还可以使您的程序更容易扩展。 新的程序员可以通过添加新的字符串和类来轻松添加功能,而无需阅读所有源代码。 ## 工厂方法示例 The example below demonstrates a factory method. The factory method (named factory) returns a new object of either type depending on the input. ```py class Car(object): def factory(type): if type == "Racecar": return Racecar() if type == "Van": return Van() factory = staticmethod(factory) class Racecar(Car): def drive(self): print("Racecar driving.") class Van(Car): def drive(self): print("Van driving.") # Create object using factory. obj = Car.factory("Racecar") obj.drive() ``` 输出: ```py Racecar driving. ``` [下载练习](https://pythonspot.com/download-oop-exercises/)