Factories are places where products or goods are manufactured. The products manufactured can be of same category only with varying properties or attributes. For example in a car factory cars are made. Those cars can be of same model or different models having different attributes like color, design etc. Similarly in OOP context, the class that implements the factory pattern (called as the factory class) has the primary objective to create other classes.

Factory pattern is generally used to instantiate and return objects of different classes that perform similar tasks or confirm to a similar interface. If you do not know what class will be instantiated at the run time and it depends upon the application logic or some settings, then you should use the factory pattern to solve the problem.

The Problem:

Suppose you have SportsCar and LuxuryCar classes. In your application depending upon some configuration or logic you need to create one of those classes. What would you do?

Generally you use condition statements to check and instantiate accordingly in your application.

But in this way each time you need to create an object of the class, you have to duplicate the conditional statements and if later you introduce another type of car say CompactCar, you’ll have to change the repeated code at many places. To solve this problem you can use a factory class to create and return an object instance from that class depending upon the setting.


The Solution:

We create a class CarFactory and it has a static method that we can call from the application passing in the settings parameter. Depending upon the parameter it will instantiate the required class and will return its instance.

Inside the application wherever you need a car object you can just use the static method from the factory class to get one.

Using the factory pattern greatly simplifies the application code and abstracts away the creation of objects of different classes. You simply use one method of the factory class and get the appropriate object. Using Factory pattern you can also makes changes easily in the future. If you need to add another car type, you just add it into the CarFactory class and it will be available for use inside your application. So it makes your app future proof.