March 20, 2013

Use of Factory Pattern and its implementation in development

Use of Factory Pattern and its implementation:

It is the most widely used pattern among all design patterns. Its falls under "Creational" design pattern category and encapsulates the object creation and instantiation logic from the client or framework who want to use it.

In simple words whenever you need an object of particular product you need not to create it via using new operator you just need to call factory to create it for yourself and you use is it via common interface or base abstract class reference.

For Example suppose you are working on paint application where you need to provide an option for drawing various shapes like line, circle etc. Each shape will have its draw method where all the drawing logic will be performed. We can create a factory for the same which will encapsulates the object creation and instantiation logic and will return the object for requested shape.
For more understanding lets have a scenario states below:


There is a base abstract shape class.

public abstract class Shape
{
 public abstract void draw ();
}

and various subclasses like line, circle etc..

class Line extends Shape
{
 public void draw () 
 {
  // draw line 
 }
}

class Circle extends Shape
{
 public void draw ()
 {
  // draw line 
 }

}

Now if you want to create object of line and circle at client or in your paint application you will write code like :


Shape line = new Line ();

Shape circle = new Circle();

This approach exposes the object creation to client which client doesn’t need he just need a reference to the line or circle object and perform operation (draw) on same.To achieve this we will create a shape Factory :

class ShapeFactory
{
 public static Shape getShape(String type)
 {
  if(type equals line)
   return new Line();
  else if(type equals circle)
   return new Circle();
  else
   Return null:
 }

}

Now we can use this factory at client side without exposing the instantiation logic:

Shape line = ShapeFactory.getShape("line");

Shape circle = ShapeFactory.getShape("circle")

No comments:

Post a Comment