2

As I understand it the factory design pattern allows objects to be created through the use of a separate object that's sole aim is to create the first one. Different types of factory can be used to create different types of object.

I understand that this hides the instantiation of the primary object however surely this is just replaced by the instantiation of the factory?

A common advantage for this design pattern is that it stops a class having to anticipate the class of objects it must create. However surely if the factory is supposed to create a specific class the main class still needs to anticipate what kind of factory to use?

I assume I'm misunderstanding the main purpose of a factory?

WalleyM
  • 172
  • 7

1 Answers1

1

The question is more complex than it seems, because there are many kinds of factories, so clients obtain and invoke them in different ways.

  • In the case of a Static Factory you are correct: the client retains a concrete dependency on a factory class. This allows the product class to be abstracted. So by anticipating the factory, the client doesn't have to anticipate the exact output of the factory.

  • In the case of an Abstract Factory, the client has it injected as a dependency, which means it should be created in the composition root. So the client knows neither the concrete factory class nor the concrete product classes.

  • In the case of a Factory Method, the client is the factory and provides a concrete product for its parent to consume.

There are more factories than these three, which may be invoked in different ways; but these three show how extreme the differences can be in the way factories are used.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
  • I was thinking of the static factory - thank you for clarifying. Surely by anticipating the factory the client anticipates the output from said factory. For example if one factory created cars and the other bikes, a client who used the car factory would anticipate a car result? – WalleyM Jun 05 '20 at 20:21
  • See reason #3 in the static factory link, "_unlike constructors, they can return an object of any subtype of their return type._" In other words, static factories can have polymorphic return types. – jaco0646 Jun 05 '20 at 20:34
  • Ok I see how that could be beneficial. Since that point is relevant too to the factory method, does it not make the need for an abstract factory class (In the gof example, the application class) redundant? Why would multiple types of factory be needed if multiple types can be returned by the concrete factory class? – WalleyM Jun 05 '20 at 23:19
  • The scope of the GoF factory patterns is too large for a comment, but you can see my take on it [here](https://stackoverflow.com/a/50786084/1371329). – jaco0646 Jun 06 '20 at 00:15