What is a Factory in OOP

让人想犯罪 __ 提交于 2019-12-30 20:28:23

问题


My understanding of "factory-related" design patterns and their OOP-implementations has always been pretty simple.

  • A "Factory method" is a method inside a class that has an interface (or an abstract class) as a return type and constructs objects implementing this interface based on some internal logic.
  • A "Factory" is a class that only contains factory methods
  • An "Abstract factory" is an interface (or an abstract class) that only contains factory methods

But I recently stumbled upon Wikipeda articles on the subject (Factory, Abstract factory) that made me somewhat confused, especially about what a "Factory" is in OOP.

Here are several quotes:

  1. A subroutine that returns a "new" object may be referred to as a "factory", as in factory method or factory function.
  2. Factories are used in various design patterns
  3. The "Abstract factory pattern" is a method to build collections of factories.
  4. A factory is the location of a concrete class in the code at which objects are constructed

which arouse some questions:

(1)&(2) Does this mean that a factory is not a class or an object, but a piece of logic?

(2) Is "Factory" not a pattern itself?

(3) What does "collection" mean here? Is it just a way of saying "you can have several factories that implement the same interface (which is an abstract factory)"?

(4) What???

Can anyone clarify what this means? Is my initial understanding of factories incorrect?


回答1:


Look at this wiki which says:

In object-oriented programming (OOP), a factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be "new".[a] More broadly, a subroutine that returns a "new" object may be referred to as a "factory", as in factory method or factory function. This is a basic concept in OOP, and forms the basis for a number of related software design patterns.

So to answer your questions specifically:

(1)&(2) Does this mean that a factory is not a class or an object, but a piece of logic?

No, it means that you can create other objects using an object(factory).

(2) Is "Factory" not a pattern itself?

There are different design patterns out of which factory pattern is one. So when you are creating objects using a factory then that patter of creating other objects is "Factory pattern"



来源:https://stackoverflow.com/questions/35765454/what-is-a-factory-in-oop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!