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 :).

--

3 comments :

[hide] Pompi said...

This is a very inspired example. Finally i undestood how the Simple Factory works.

on September 29, 2007 at 4:05 AM
[hide]

How to Reply to this comment

To reply to this comment please ensure that one of the following lines:
  • @5085560559247513473.0
  • @Pompi
is the first line of your comment.
Click here to enter your reply
[hide] Unknown said...

Hi, great guide!

Just as a note, I think you forgot a curly brace at the end of PepsiFountainFactory to close the createDrink function. I know this is meant to be an example, so it's not really that big of a deal... But I just figured you might want to know.

on May 29, 2009 at 6:14 PM
[hide]

How to Reply to this comment

To reply to this comment please ensure that one of the following lines:
  • @1230307366723856201.0
  • @Unknown
is the first line of your comment.
Click here to enter your reply
[hide] Anonymous said...

Your blog keeps getting better and better! Your older articles are not as good as newer ones you have a lot more creativity and originality now keep it up!

on January 3, 2010 at 6:18 PM
[hide]

How to Reply to this comment

To reply to this comment please ensure that one of the following lines:
  • @6054754455793719297.0
  • @Anonymous
is the first line of your comment.
Click here to enter your reply