Thursday, August 25, 2011

Factory Design Pattern


The essence of the Factory method Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."


In simple words, if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.

The Factory Method pattern uses an abstract class called a factory to instantiate new objects.


Factory methods encapsulate the creation of objects.

Creating objects without exposing the instantiation logic to client

Referring to the newly created objects through a common interface.

So basically the factory pattern is used wherever the sub classes are given the privileged of instantiating a method that can create an object.





UML class diagram




 Logical working of Factory pattern

 



Example Code:-


Let’s suppose an application asks for entering the name and sex of a person. If the sex is Male (M), it displays welcome message saying Hello Mr. and if the sex is Female (F), it displays message saying Hello Ms .


// Factory pattern -- Real World example

using System;

namespace Factory_Pattern_By_Manish_Agrahari
{
    public class Person
    {
        public String name;
        private String gender;

        public String getName()
        {
            return name;
        }

        public String getGender()
        {
            return gender;
        }
    }


    public class Male : Person
    {
         public Male(String fullName)
        {
            Console.WriteLine("Hello Mr. "+fullName);
        }
    }

    public class Female : Person
    {
         public Female(String fullNname)
        {
            Console.WriteLine("Hello Ms. "+fullNname);
        }
    }

    public class Client
    {
         public static void Main()
        {
            Client factory = new Client();
            factory.getPerson("Manish Agrahari", "M");

            Console.ReadLine();
        }

        public Person getPerson(String name, String gender)
        {
            if (gender.Equals("M"))
                return new Male(name);
            else if(gender.Equals("F"))
                return new Female(name);
            else
                return null;
        }
    }
}

Output:-

Hello Mr. Manish Agrahari




Miscellaneous Examples

.NET Framework
  • System.IO.File.Create() Factory Method

Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.

using (FileStream stream = File.Open("path", FileMode.OpenOrCreate))
{
}
  • System.Xml.XmlWriter.Create() Factory Method

Represents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data.

using (XmlWriter writer = XmlWriter.Create("outputFileName"))
{
}
  • System.Convert.To????

Converts a base data type to another base data type.

int result = System.Convert.ToInt32("10");
  • System.Activator

Creates an instance of the specified type using the constructor that best matches the specified parameters.


public static object GetObject(Type type)
{
  return Activator.CreateInstance(type);
}







Related Posts:-

Design Pattern

Factory Design Pattern

Abstract Factory Design Pattern

Difference between Factory and Abstract Factory Pattern

2 comments:

Basavaraja K said...

Thanks Manish...Very good explaination..

Basavaraja K said...

Good Explaination.. Thanks Manish..