This is the most commonly used design pattern. Same as other design patterns this also solves some software problem. This pattern is the base of Factory Method pattern and Abstract Factory design pattern.
The objective of this article is to explain you the basic of factory, where and how it is implemented.
Definition
- Creates objects without exposing the instantiation logic to the client.
- Refers to the newly created object through a common interface.
Approach
Let’s see how factory solves design problem. Let’s create a client application for showroom where user comes and asks for the specification of a car.
Solution
- For this we will create an abstract class of car, which will be implemented by other cars.
- Now let us implement this with few cars.
- Let us create a client application where user selects a car and will see all the specifications of that car.
Let’s run this:
This is how we will do to achieve this showroom application. This is working as expected.
Problem statement
But there are few problems with this code:
- Client aware of code.
- Lots of new.
- Lots of condition.
- If new car comes the client code needs modifications.
All the above can be fixed with factory design pattern.
Let’s fix:
To fix this with Factory,
- Let us create a factory class.
- Client code also needs to be modified as we need to fix in client.
Let’s run this code.
We are able to remove the object creation/ instantiation logic from client moving to Factory with the above approach.
The above understanding is enough
to explain the basic implementation of Factory.
Extended :More Changes and better and advanced implementation that can be done to fix all the issues we identified with below factory code:
As you notice in the getCar() method the return statement is,
Return car.CreateCar();
This is required to get the instance of the requested car from the factory to client code. This needs some modification in the abstract Car class and the implementation class.
Client Code
- With this code more cars can be added by just adding them in register method of Factory.
- Removed the condition, with more flexible code.
- Also, remove all the new keyword.
The following url explains all about factory.