Centralised object creation

True Factory Design Pattern

Created by Freepik - www.freepik.com

Disclaimer : The content of this blog are my views and understanding of the topic. I do not intend to demean anything or anyone. I am only trying to share my views on the topic so that you will get a different thought process and angle to look at this topic.

The design patterns help solving common issues. Factory pattern helps in resolving the issues relating to object creation in an application. Hence it is grouped under Creational Design Pattern.

In normal enterprise java application there are many different factories we can think. A CRUD application would essentially have set of DTOs (Data Transfer Objects) and Entities, few service classes, DAO (Data Access Objects) classes. I have worked on spring framework based applications. Hence creating and managing objects is done by spring. I think its a global factory with different options. I will touch upon a simple centralised factory which handles the responsibility of creating objects. This means within my application nowhere else should I be able to create an instance of the classes which I am managing via the factory.

Take an example of Car factory. I setup a factory for managing instances of 2 types of cars : AUDI and BMW. I want that creation of the objects should be managed by a factory so that this is encapsulated from the rest of the application. I will illustrate this with an example.

I have a package called com.factorypattern. It contains the classes : Car, Audi and BMW

Access specifiers for Audi and BMW class declaration are default which means they are package private. Moreover the constructors of these classes are also having same access specifiers. I introduce a factory class in the same package which will expose the required apis for creating instances of Audi and BMW classes.

This way I can now create instance of the Audi and BMW via CarFactory only. I would get and error if I try to instantiate the classes directly since they are package private.

PROS

Centralisation of object creation which helps in controlling the number of objects created of specific type or the types managed via that factory

CONS

It works only for homogeneous objects which we can package together. If the objects are separated in different package then it won't serve the purpose

KEEP THINKING !