Factory Design Pattern

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

  1. For this we will create an abstract class of car, which will be implemented by other cars.

    create an abstract class of ca

  2. Now let us implement this with few cars.



  3. Let us create a client application where user selects a car and will see all the specifications of that car.

    implement this with few of cars

Let’s run this:

run

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:

  1. Client aware of code.
  2. Lots of new.
  3. Lots of condition.
  4. 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,

  1. Let us create a factory class.

    create a factory class

  2. Client code also needs to be modified as we need to fix in client.

    Client code

Let’s run this code.

We are able to remove the object creation/ instantiation logic from client moving to Factory with the above approach.

output

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

 

  1. With this code more cars can be added by just adding them in register method of Factory.
  2. Removed the condition, with more flexible code.
  3. Also, remove all the new keyword.

The following url explains all about factory. 


Similar Articles