Showing posts with label factory method. Show all posts
Showing posts with label factory method. Show all posts

Thursday, July 15, 2010

Good reason to use Factory Methods

As much as i enjoy learning and understanding design patterns, i find it pretty hard to apply them in practical situations and get an improved piece of code from most perspectives, that is readability, testability, maintainability and other 'bilities. What i want to show here is the perfect opportunity for me to implement the Factory Method pattern.
This is the scenario: I had a table in a database where each record represented a specific process that could be performed by an application. I've decided to take the OOP way and create a base Process class and derive all processes from it. Then the processes needed to be instantiated based on records in the database, so i had to connect strongly-typed classes to strings in a SQL table. This is where the factory method came in.
Instead of checking the record name for each record and decide what class type to create, i just created a static method in the base Process class called CreateProcess as such:
public abstract class Process 
{
   //some code here
   public static Process 
CreateProcess(string ProcessName)
      {
         switch(ProcessName)
         {
            case "DoSomethingProcess":
               return new DoSomethingProcess();
            //check all known cases
            default:
               throw new NotImplementedException(
                 string.Format("The process {0}" + 
" does not have a mapped implementation.");
         }
      }
}