Simple Factory in Java

April 23, 2014

Factories are used to handle the details of creating objects. Formally put, factories are used to encapsulate object creation. There are 3 variants of implementing factories namely Simple Factory, Factory Method and Abstract Factory.

Although Simple Factory is not an official GoF design pattern it's still worth to know since It'll be useful when understanding Factory Method pattern and Abstract Factory which will be explained in the next post.

Implementation example of Simple Factory in Java Swing API - javax.swing.BorderFactory


Simple Factory

Basic idea is to separate object instantiation logic from the client and grant reference to instantiated objects through a common interface, ie. clients need not to know how the products are created, they just need to use them. The classes which are used to instantiate objects are called creator classes and classes which are used to construct the objects are called product classes.

Take a look at the following class diagram where there is VehicleFactory which produces Cars and Bikes. (yellow color corresponds to creator classes and green corresponds to product classes)


Let's put the above scenario into code. Car and Bike classes implement Vehicle interface which is referenced by the Client class as the common interface.

VehicleFactory class uses the static method createVehicle() to instantiate objects. Because of the static method this is also called a Static Factory. But it does not necessarily have to be static (but most often static) or be restricted to just one method. There can be separate methods to instantiate different objects, for instance, createBike() method for instantiating Bike object and createCar() method for instantiating Car object.

Client receives references of Bike and Car objects though Vehicle interface using VehicleFactory class.

There are few issues regarding the implementation of Simple Factory. One of the most important issues is that this design violates Open-Close Principle which states that software entities (classes, modules, etc) should be open for extension, but closed for modification.

Consider the above example. If we need to add a new product, for instance a Ship class, then VehicleFactory class must be to be modified. This is a direct violation of the open-close principle. This issue has been addressed in Factory Method pattern by leaving the instantiation to subclasses.

Thank you for reading.

No comments:

Post a Comment