Search code examples
design-patternsfactory-pattern

How does using the factory design pattern stop a class having to anticipate the class of objects it must create


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?


Solution

  • 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.