以下是一些补充信息,可能有助于更好地理解其他几个较短但技术上正确的答案。
从最严格的意义上讲,类工厂是一个函数或方法,它根据输入参数或全局上下文确定的某些条件创建或选择一个类并返回它。当type直到运行时才能确定所需对象的数量。当类本身就是所使用语言(例如 Python)中的对象时,可以直接完成实现。
Since the primary use of any class is to create instances of itself, in languages such as C++ where classes are not objects that can be passed around and manipulated, a similar result can often be achieved by simulating "virtual constructors", where you call a base-class constructor but get back an instance of some derived class. This must be simulated because constructors can't really be virtual✶ in C++, which is why such object—not class—factories are usually implemented as standalone functions or static methods.
Although using object-factories is a simple and straight-forward scheme, they require the manual maintenance of a list of all supported types in the base class' make_object()
function, which can be error-prone and labor-intensive (if not over-looked). It also violates encapsulation✶✶ since a member of base class must know about all of the base's concrete descendant classes (now and in the future).
✶ Virtual functions are normally resolved "late" by the actual type of object referenced, but in the case of constructors, the object doesn't exist yet, so the type must be determined by some other means.
✶✶ Encapsulation is a property of the design of a set of classes and functions where the knowledge of the implementation details of a particular class or function are hidden within it—and is one of the hallmarks of object-oriented programming.
因此,最好/理想的实现是那些可以处理新候选类的实现自动地添加它们时,而不是仅将某个有限集硬编码到工厂中(尽管这种权衡通常被认为是可以接受的,因为工厂是唯一需要修改的地方)。
James Coplien 1991 年出版的书高级 C++:编程风格和习惯用法详细介绍了在 C++ 中实现此类虚拟泛型构造函数的一种方法。还有更好的方法可以使用C++ 模板,但这在本书中没有涉及,这早于它们被添加到标准语言定义中。事实上,C++ 模板本身就是类工厂,因为每当使用不同的实际类型参数调用它们时,它们都会实例化一个新类。Update:我找到了 Coplien 1998 年为 EuroPLoP 撰写的一篇论文,标题为C++ 习语除其他外,他将书中的习语修改并重新组合成 1994 年的设计模式形式设计模式:可重用的面向对象软件的元素书。特别注意虚拟构造函数部分(使用他的信封/信件模式结构)。
另请参阅此处问题的相关答案Python 中的类工厂以及 2001 年 Dobb 博士关于使用 C++ 模板实现它们的文章,标题为抽象工厂,模板风格.