Wednesday, February 15, 2012

Creational Patterns - 1.Factory Method

This is the simplest of all the GoF(Gang Of Four) Design patterns. It deals with the task of creating an object for a class. Instead of creating objects in our business classes, we are delegating the task to a Factory class. This will help us to maintain and manage the objects without affecting the business flow.

Example Use Case:-

Consider, we are in a process of creating a Car for ABC Company as mentioned below,
Car car=new Car();
car.createCar();

In future, companies like PQR,XYZ,etc may ask us to create cars for them.
So, we need to maintain the create() for each and every company in our Car class itself.

Car car=new Car();
car.createABCCar();
car.createPQRCar();
car.createXYZCar();


The above approach would create a tight dependency over the Car creation process.
We can solve this problem and create a loose dependency with the following design:-




When we create the cars based on the above design, it would be easier to accommodate any number of new companies for creating their cars. For providing cars to PQR, we need to create a PQRCar Class by inheriting Car and an implementation to the Factory for creating the PQRCar.
The business logic for creating a car would be something similar to,

CarFactory factory=new ABCCarFactory();
CarFactory factory=new PQRCarFactory();

Car car=factory.createCar();


Thus, the car creation logic will be handled by the CarFactory based on the instantiation
of the factory.

No comments:

Post a Comment