Click here to Skip to main content
Click here to Skip to main content

Factory Pattern using Generics

, 12 Jan 2011
Rate this:
Please Sign up or sign in to vote.
Factory Pattern using generics

Introduction

This article reveals some good use of design patterns using generics. Think if these design patterns are made using generics in .NET, it can work as wonders. You can create your own design pattern class library which could be then made re-usable in any project. I will be showing Factory Design Pattern using generics in .NET.

Background

For those who don't know Factory Design Pattern, please refer to this article of GOF available at below mentioned link:

Using the Code

Now let's start with some coding stuff. First, I will show you the implementation of Factory pattern without using generics. Then, we will go about changing the same factory pattern using generics and you will see the difference. So, we start with creating two simple classes, i.e., ReportGenerator and ReportAnalyser which share a common interface implementation IActivity.

NOTE: I have taken ReportGenerator and ReportAnalyser classes for example purposes only.

public interface IDBActivity 
{
 void Process();
}

public class Enumeration
{
    public enum ModuleName
    {
        ReportGenerator = 1,
        ReportAnalyser = 2
    }
}
    		
public class ReportGenerator : IActivity 
{
  public void Process()
  {
    // Do some coding here ...
  }	                               
}

public class ReportAnalyser : IActivity 
{
  public void Process()
  {
     // Do some coding here ...
  }						                                
}        

Now comes the implementation of Factory Pattern. To achieve this, let's create a class FactoryClass.

public class FactoryClass
{
  public static IActivity CreateInstance(Enumeration.ModuleName enumModuleName)
  {
     IActivity objActivity = null;
     
     switch (enumModuleName)
     {
          case Enumeration.ModuleName.ReportGenerator:
                 objActivity = new ReportGenerator(); 
                 break;
          case Enumeration.ModuleName.ReportAnalyser:
                 objActivity = new ReportAnalyser();
                 break;
          default:
                 break;
     }
     return objActivity;
  }
}

From the above code, we are creating an instance of ReportGenerator or ReportAnalyser class as per enum value passed and assigning it to IActivity object. Hence, when client will call CreateInstance method, it will just receive IActivity object rather than ReportGenerator or ReportAnalyser object.

This is what we call core of Factory Pattern where client is creating objects of ReportGenerator or ReportAnalyser without specifying exact class of the object. The below code snippet shows how client will use Factory Pattern by calling our FactoryClass' CreateInstance() method.

private void btnProcess_Click(object sender, EventArgs e)
{	
    IActivity objActivity = null;

    objActivity = FactoryClass.CreateInstance(Enumeration.ModuleName.ReportGenerator);
    objActivity.Process();
}

Now comes the important part of this article where I will be showing you how to use generics within Factory Pattern. Okay, let's first create a new Windows class library project and name it as DesignPatterns. Within that project, create a new class and name it FactoryPattern.
Inside that class, please write the code as mentioned below:

public class FactoryPattern <K,T> 
        where T : class, K, new()
{
    public static K CreateInstance()
    {
        K objK;

        objK = new T();

        return objK;            
    }
}	  	

You might be wondering what's all this ??? Smile | :) . Okay, I will explain the concept to you. Here, I have created FactoryPattern class using generics. It takes two parameters, i.e., "K" and "T". T parameter has "where" constraint which depicts that T should be a class, it should be inherited from K and its instance can be created. Huh ... too much of conceptual. Let's analyze this line where T : class, K, new():

  • where T:- means you want some constraints to be implemented when client passes T as a type parameter
  • class:- means that T parameter passed should be a class
  • K:- means that T parameter passed which is a class should always be inherited from K type parameter
  • new():- means that you can create instance of T parameter passed in FactoryPattern class

I believe this makes sense and things are now more clear. So now I know the question that will be coming in your mind is how to fit this class in Factory Pattern implementation?? You just need to make some changes in the code written in FactoryClass.
Please find the below code snippet which will make things more clear:

public class FactoryClass
 {
   public static IActivity CreateInstance(Enumeration.ModuleName enumModuleName)
   {
      IActivity objActivity = null;
      
      switch (enumModuleName)
      {
           case Enumeration.ModuleName.ReportGenerator:
                  /* Old coding ...
                  objActivity = new ReportGenerator(); 
                  */
                  objActivity = FactoryPattern<IActivity, 
			ReportGenerator>.CreateInstance();
                  break;
           case Enumeration.ModuleName.ReportAnalyser:
                  /* Old coding ...
                  objActivity = new ReportAnalyser();
                  */
                  objActivity = FactoryPattern<IActivity, 
				ReportAnalyser>.CreateInstance();
                  break;
           default:
                  break;
      }
      return objActivity;
   }
 }   

All that is using generics with Factory Pattern. Now can you figure out the meaning of the line where T : class, K, new().
ReportGenerator is a class. It is inherited from IActivity interface. You can create an instance of ReportGenerator class. Since you have created FactoryPattern class using generics and construction logic of objects all lies at central point, you can now use your
FactoryPattern class in all your future projects. You need not have to think / worry about the creation of object, just pass the appropriate parameters and the object is created in FactoryPattern class.

Think about other Design Patterns you can implement using Generics... sounds challenging !!

I hope this article will be of some use to you.. Since this is my first article, I could have made mistakes, if so, then kindly rectify it.
You can download the source code. It's developed in .NET 3.5.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Samir Dedhia
Software Developer (Senior)
India India
No Biography provided

Comments and Discussions

 
GeneralMy vote of 2 PinmemberQwertie17-Jan-11 11:54 
GeneralMy vote of 1 Pinmembernrutter17-Jan-11 4:25 
GeneralThis is not a Factory Design Pattern PinmemberCrawfis17-Jan-11 4:01 
GeneralRe: This is not a Factory Design Pattern PinmemberKpaxOdrade18-Jan-11 18:45 
GeneralMy vote of 1 PinmemberCrawfis17-Jan-11 3:59 
QuestionWhy not IoC? PinmemberS. M. SOHAN13-Jan-11 9:39 
QuestionWhy 2? Pinmemberpeterchen12-Jan-11 7:52 
GeneralMy vote of 2 PinmemberRobert Rohde12-Jan-11 7:25 
GeneralRe: My vote of 2 PinmemberSamir Dedhia19-Jan-11 17:51 
AnswerRe: My vote of 2 PinmemberWolfgang_Baron23-Jan-11 13:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 12 Jan 2011
Article Copyright 2011 by Samir Dedhia
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid