What is a Factory Pattern?
Factory Pattern is also among the most commonly used design patterns. Instantiating an object with the
new() operator couples the code tightly to the concrete implementation leading to less flexible code. The factory design pattern defines an interface for creating an object known as a factory method. It then uses this method to create the object.
The factory pattern allows you to create an object without specifying the exact class of object that needs to be created.
Advantages of Factory Design Pattern
- The factory design pattern removes the tight coupling in the application by delegating the instance creation to a factory method. The clients do not need to know the concrete implementations, it can code to the interface. Loose Coupling is the biggest advantage of Factory Design Patterns.
- It embodies the object oriented design principle of coding to an interface and not an implementation. Thereby making it easier to unit test the application.
- Creator Class : This is the class that has the factory method, and that returns an object of the concrete product class.
- Product Class : This is the interface or abstract class, from which the concrete product classes are supposed to inherit.
- Concrete Product Classes : One or more classes that should abide by the contract of the Product class. This is the class whose object ultimately gets created.
Let us take an example application where we have to draw a shape.
For this the first step would be to create the object of whichever shape that needs to be drawn. And then the draw method on this shape needs to be called.
Typical method to do this would be something like
If we have to now draw a rectangle, the above code would need to be modified to
If we want to refactor the above code to use the Factory Pattern, we would have something like a base class
Shape, which can be inherited by both
Rectangle subclasses. We will have a
ShapeFactory class that will give the object of the appropriate class based on input.
Let us look at the implementation below:
First, let us define the base product class Shape. Here we have made it as a Interface, but it can also be an abstract class.
Next let us define define the concrete product classes.
You can find the complete code on github.
Factory Pattern in Java Library
java.util.ResourceBundle#getInstance() method uses the Factory design pattern. You can read more about the method in the Oracle docs.