Thursday, February 16, 2012

Creational Patterns - 2.Abstract Factory

Abstract Factory will be the right choice, when you are dealing with different types of objects sharing some common features. We can, abstract those features and define seperate factory implementations for creating the objects.

In otherwords, this is a factory of factories.

Example Use Case:-

This will be an extension to the factory method use case.
Now, the ABC Company needs some variety of cars. They are in need of Sedan Cars and HatchBack Cars. Similarly, PQR and XYZ companies are also demanding the same.

How can we handle this ?

CarFactory factory=new ABCCarFactory();
factory.createCar();


This block of code would be fine for a normal requirement as discussed in factory method
use case. For this new requirement we need some thing like,

CarFactory factory=new ABCCarFactory();
factory.createSedanCar();
factory.createHatchBackCar();


In future, ABC company may ask for SUV cars. so, we need to think for a seam less modification to the design.
Now,we categorize the cars based on their types(Sedan,Hatchback,SUV,etc).Let the companies(ABC,PQR,etc) write their own implementation of the types.

The design looks as specified below,


We have seperate CarFactories for every company. ABCCarFactory deals with the sedan and hatchback cars of ABC Company only.

This will enable us to add new Factories for new companies without any modification to the existing behavior. Similarly, new vehicle types like SUV can also be introduced without much
effort.

No comments:

Post a Comment