Jul 7, 2013

Factory Design Pattern

1 comment
What is it?
The Factory Design Pattern is of type Creational Pattern. The official definition for the Factory pattern is: 
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

This pattern is used to replace a class constructor(s), allowing the type of object to be instantiated to be determined at run-time as opposed to design-time, and is used to control a class instantiation. The use of this design pattern reduces the coupling between classes, and offers much more flexibility in the future if the requirements of your application changes, which often happens. One tangible benefit of the Factory pattern is it allows the client to focus on its role in the architecture because it allows for separation of the creation & instantiation of objects from the client.

Implementation:
To implement the Factory design pattern we will create an Interface which will define the classes that will be instantiated by our factory class. Here we're using a very simple example but know this is a very powerful design pattern and can be expanded to more complex structures & objects. So, for this we will have an interface (IEmployee) that has a single value, Salary that all our objects will implement (keep in mind this is just an example to show how this design pattern works and can be implemented):

using System;

namespace DesignPatterns.FactoryPattern
{
    public interface IEmployee
    {
        double Salary { get; }
    }
}
Now we have 3 classes (factory objects) to demonstrate different employee types. We have Programmer, DBA and Manager which all implement our IEmployee interface, utilizing a single read-only property


Programmer:
using System;
namespace DesignPatterns.FactoryPattern
{
    public class Programmer : IEmployee
    {
        public double Salary
        {
            get { return 50000; }
        }
    }
}

DBA:
using System;

namespace DesignPatterns.FactoryPattern
{
    public class Dba : IEmployee
    {
        public double Salary
        {
            get { return 60000; }
        }
    }
}

Manager:
using System;

namespace DesignPatterns.FactoryPattern
{
    public class Manager : IEmployee
    {
        public double Salary
        {
            get { return 100000; }
        }
    }
}

Now we need a factory class to handle the instantiation of our factory objects. Although in our example our factory manager class only has a single method (factory method), this method completely encapsulates the creation of our factory objects. Our factory method is declared as static so no instance our factory manager need be made: 

Factory Class:
using System;

namespace DesignPatterns.FactoryPattern
{
    public class EmployeeFactory
    {
        public static IEmployee Create(EmployeeType type)
        {
            IEmployee emp = null;
            switch (type)
            {
                case EmployeeType.Manager:
                    emp = new Manager();
                    break;
                case EmployeeType.DBA:
                    emp = new Dba();
                    break;
                default:
                    emp = new Programmer();
                    break;
            }

            return emp;
        }
    }

    public enum EmployeeType
    {
        Programmer,
        Manager,
        DBA
    }
}

Ok we now have our factory defined and created, so how do we use it? We will generate a new employee for each EmployeeType in a loop using the factory class, then print out salary. This is done without the client ever knowing what object type is being instantiated, and this is because our factory class handles the instantiation of any EmployeeType that is created:
private void btnFactory_Click(object sender, EventArgs e)
{
   Dictionary employees = new Dictionary();

  // Create a new Employee for each available employee type. 
  // Each item is insatantiated without the client needing to know what type of object is being created
  // (this is handled by the factory method)
  foreach (EmployeeType type in Enum.GetValues(typeof(EmployeeType)))
  {
      employees.Add(type, EmployeeFactory.Create(type));
  }

  // now let's iterate through our dictionary and diplay the base salary for each factory object
  foreach (EmployeeType type in employees.Keys)
  {
     rtxtOutput.AppendText(string.Format("Salary for employee of type '{0}' is {1:C}", type, employees[type].Salary));
     rtxtOutput.AppendText(Environment.NewLine);
   }
}

Output:
Salary for employee of type 'Programmer' is $50,000.00
Salary for employee of type 'Manager' is $100,000.00
Salary for employee of type 'DBA' is $60,000.00

Factory Pattern in .Net BCL : GetEnumerator() returns an specific enumerator type based on the collection class. Well that is how the Factory Design Pattern works and is used, as we seen it can be extremely powerful and helpful (especially when dealing with complex creation processes, such as when the creation depends on input from the user or from some sort of configuration file) when designing complex software.

1 comment :