What is a Factory in OOP

2020-04-06 03:19发布

问题:

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"