Factory Design Pattern

People have been appreciating the effort I am putting in each post these days. Feels good.

Moving on with another design pattern, we have the ‘Factory Design Pattern’. It is also known as the Simple Factory Design Pattern. There exists a very similar pattern named ‘Abstract Factory Design Pattern’. The difference between the design patterns will be discussed once I post about Abstract Factory Design Pattern in my next post.

Lets use the Factory Design Pattern to solve a simple problem.

Problem:

Lets design a beverage making machine for a cafe. This machine should produce tea, coffee or lemonade. Since, the cafe keeps updating their menu, the solution must be flexible enough to accommodate new beverages in the future.

 

Design:

When should the factory design pattern be used?

  1. When classes are to be generated at runtime.
  2. The factory must return  one of several objects sharing a common super class.
  3. Also, when you don’t want the client to know every subclass.

In order to centralize the object creation, lets create an ObjectFactory for beverages, say BeverageFactory.

  1. BeverageFactory: A singleton factory having a method say [[Beverage makeBeverage(String typeOfBeverage)]]. The method returns an object of Beverage. Thus, makeBeverage returns any sub-class of Beverage. The makeBeverage method holds the object creation strategy.
  2. Beverage: An abstract class which all the beverages will extend.

 

Class Diagram:

Factory Design Pattern

 

Download the implemented code:

https://github.com/73ddy/design_patterns/tree/master/FactoryPattern

 

Pros and Cons:

Advantages:

  1. The code for object creation is compact and encapsulated within a single factory.
  2. Choice of object creation can be made at runtime.
  3. The system turns loosely coupled, and creation doesn’t depend on the classes of the products to be created.

Disadvantages:

The only disadvantage with the factory pattern may introduce unnecessary complication into the code. This disadvantage is basically a reference to the YAGNI principle.

Advertisements

About Gaurav

I'm Gaurav; friends call me Teddy, n i'm shivi fr my family!! A java enthusiast who likes experimenting with what he knows. View all posts by Gaurav

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: