Saturday, January 15, 2011

Factory Pattern

What does a factory do? It creates something, it constructs something. Therefore the category of this pattern is Creational Pattern, no surprises!

For the sake of simplicity, let's say that a car consists of three components: Engine, Chassis, and Steering. Naturally, you can't have the same types of Engine, Chassis or Steering in each car, because then the cars would all be the same. It won't do to mix-and-match components, either. You need all Honda parts to go with the Honda, and all BMW parts to go with the BMW, etc. The different parts of the cars don't need to do the same thing, either: they need merely conform to an interface. Let's encapsulate the decision making process for assigning the parts when you build a car.
Should the main car building program care what kind of car is being built? No, it shouldn't. It should just expect the car to behave as all cars should, and not care about the specifics

Imagine you have a code that has multiple if and else statements where you create object of different classes depending on the conditions.  You will end up with lots of use of 'new' keyword.

if(type = "honda")
       hondaObj = new Honda()
Else if(type = "bmw"
      bmwObj = new BMW()
….
….
so on...

 This definitely makes the code little complex. Also if in future you have one more condition to be added in the pile, you create another object based on that type. One more problem with this approach is that you have to know the type of these classes to create their objects and this problem becomes worse when such a code is written by some client side application, which means that client application has to know these types in order to create and use these objects, which is a bad design and definitely not scalable.

Solution to these two issues is…
  1. Make an interface called IVehicle and drive the concrete classes from this class and client will know only this interface and doesn’t have to know the names of the classes..
  2. Introduce a factory class which will be responsible for creating the classes which will know the different classes, therefore you supply the type and it returns the object.

This solves both the issues mentioned above. The above code now looks like below…
IVehicle  objVehicle;
objVehicle = factory.GetVehicle(type);
objVehicle.GetModelNUmber();

Keep thinking….

No comments:

Post a Comment