Wednesday, December 18, 2013

Factory method design pattern - Creational design pattern

Factory method

Its a Creational design pattern.
Definition: “The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.”
Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.

Easy way
easily we can say that it’s a method that provides the object of a class at run time. Normally it happens by passing argument to that method and on the basis of that argument method decide which object to create.

Example :-
You have  ice-cream factory and having two flaour and want to add one more .  task of this method (Factory) will be to fulfill the desired demand that a customer makes. So basically Factory Method Pattern is just a method which actually fulfills our demand of object creation at run-time.

Same like for shape also See below UML diagram source http://www.tutorialspoint.com



Code in JAVA

Here are classes 
interface IShape
{
    string draw();
}
class Circle: IShape
{
    public string draw()
    {
        return "Circle";
    }
}
class Rectangle : IShape
{
    public string Functionality()
    {
        return "Rectangle";
    }
}
class Square : IShape
{
    public string Functionality()
    {
        return "Square";
    }

Factory method
static class Factory
{
   /// This is the Factory method
  
   public static IShape Get(int id)
   {
       switch (id)
       {
           case 0:
                return new Circle();
           case 1:
                return new Rectangle();
           case 2:
                return new Square();
           default:
                return null;
        }
   }

Factory method is just like regular method but when we are talking about patterns it just returns the instance of a class at run-time depending upon the input method gets.




0 comments:

Post a Comment

About

Powered by Blogger.