WHAT IS A FACTORY?
As one of the creational patterns, the factory's purpose is to create objects. The creational logic is
encapsulated within the factory and either provides a method that returns a newly created object
(factory method pattern) or delegates the creation of the object to a subclass (abstract factory
pattern). In both cases, the creation of the object is abstracted away from where it will be used.
The client need not be aware of the different implementations of the interface or class. The client
only needs to know the factory (factory method or abstract factory) to use to get an instance of one
of the implementations of the interface. Clients are decoupled from the creation of the objects.
The decoupling occurs as the result of applying the dependency inversion principle and brings many
practical advantages, of which the most important is the decoupling of higher‐level classes from
lower‐level classes. This decoupling allows the implementation of the concrete classes to be changed
without affecting the client, thus reducing coupling between classes and increasing l exibility.
The factory pattern gives us the opportunity to decouple object creation from the underlying system
by encapsulating the code responsible for creating the objects. This approach simplii es our life when
it comes to refactoring as we now have a single point where the refactoring changes happen.
Often the factory itself is implemented as a singleton or as a static class because normally only one
instance of the factory is required. This centralizes factory object creation, allowing for greater
organization and maintainability of source code and the reduction of errors when changes and
updates are made.
NOTE Dependency Inversion Principle:
1. High‐level modules should not depend on low‐level modules. Both should
depend on abstractions.
2. Abstractions should not depend on details. Details should depend on
In Java EE, dependency injection is employed to deliver the decoupling of higher‐level classes from
lower‐level classes when implementing the factory pattern. The combined use of the @Producers
and @Inject annotations makes their implementation relatively simple.
The GoF 2 book describes the factory method pattern as such: “Dei nes an interface for creating an
object, but lets subclasses decide which class to instantiate.” Head First Design Patterns 3 adds that
the “factory method lets a class defer instantiation to subclasses.”
Factories minimize the usage of the new keyword and can encapsulate the initialization process and
the different concrete implementations. The ability to centralize those needs minimizes the effect of
adding or removing concrete classes to the system and the effects of concrete class dependencies.
The factory method class diagram is shown in Figure 6-1.