Sunday, August 12, 2007

Simple Factory

Today we will be understanding the Simple Factory.

So let's first have a simple program to make where we will use the Factory Method pattern.

The requirements of our program are fairly simple:

We have a client and she wants us to make a software for a Pepsi Fountain machine that serves Pepsi, 7UP and Mirinda.

This is really a simple program and we can provide the solution very quickly:

Notice the segment in bold. If we have to add another drink, say Diet Pepsi, to this Fountain we have created we would need to add another if-else block and another constant (if we wanted to maintain a minimum
standard of good practice :) ).

It is time to get familiar with one of the more important suggestions while using design patterns:

"Encapsulate what varies"

We notice that the bold block in the PepsiFountain class is the one likely to vary when the client changes her
requirements. So it is best to remove that block from the execution block in the method.There are quite a few alternatives for us. One of the more commonly chosen techniques is to remove that segment and move it to a utility class with a static method as follows:

What we've just created is known as a 'Simple Factory'. It really isn't a design pattern and is very often confused with the Factory Method Pattern. Simple Factories are very commonly used techniques and should be used when as the name suggests requirements are fairly simple :).