Working with Factory Design Pattern using C#
page 1 of 1
Published: 20 Apr 2006
Unedited - Community Contributed
In this article, Vishal demonstrates the concept of Factory Design Pattern using C#.
by Vishal Patil
Average Rating: 
Views (Total / Last 10 Days): 12788/ 23


The Factory design pattern is useful when a class cannot anticipate the class of objects it must create or when a class wants its subclasses to specify the objects it creates.  It is also useful when you want to delegate responsibility to one of several helper subclasses and localize the knowledge of which helper subclass is the delegate.

Its intent is to define an interface for creating an object, but let the subclasses decide which class to instantiate.  The Factory Method allows a class to defer instantiation to the subclasses. (Reference

Factory Design Pattern allows applications to provide encapsulation by hiding the complex components and their dependencies from the client.  It writes an object creation code in a centralized location, called the Factory class, which helps to reduce the code redundancy in the application.  The client code instantiates the Factory class and passes some parameter values to the Factory class.  The Factory class instantiates the required object, based on the received Parameter values, and returns it to the client. This way, Encapsulation is preserved and also helps to build reusable components.

In the case of the following simple .NET example, we can consider a System.Convert class. This class contains a set of conversion functions, few of them are demonstrated below.

Listing 1

int intValue = Convert.ToUInt16(true);

In this Listing, we have passed the true Boolean value to the Convert.ToUInt16 method. This method internally checks parameter data type.  It then converts this Boolean value into the integer value “1” and returns it.

Similarly, in the below code, Convert.ToUInt16 method accepts the false Boolean value and returns integer value “0”.

Listing 2

int intValue = Convert.ToUInt16(false);

We can even consider a Convert.ToBoolean function which behaves similarly.

Classic examples of .NET are enumerators, such as CommandType.StoredProcedure, CommandType.TableDirect and CommandType.Text.

Listing 3

SqlCommand cmdobj = newSqlCommand(StoredProcedureName, ConnectionString);
cmdobj.CommandType =CommandType.StoredProcedure;
SqlCommand cmdobj = new SqlCommand(TableName,ConnectionString);
cmdobj.CommandType = CommandType.TableDirect;
SqlCommand cmdobj = new SqlCommand(SelectText,ConnectionString);
cmdobj.CommandType = CommandType.Text;

In the above listing, notice that based on the CommandType set to the SqlCommand object, it executes one of the following- Stored Procedure, Table or Select Query. This demonstrates that inside a SqlCommand object, logic exists which based on the Enumerator value of CommandType, executes Stored Procedure, Table or Select Query.

A non-software example that demonstrates this pattern would be a restaurant. Restaurants serve a variety of items which they list in the menu.  The restaurant's waiter provides a menu to the customer and, based on the items available in the Menu, the customer selects the items and orders them. These selected items are prepared and served to the customer by the waiter.

If you map this non-software example against the factory design pattern, we can say:

Items, as the subclasses, are served to the customer by a waiter and its preparation is hidden from the customer.

The waiter, as the Factory class, takes the customer's order based on the items available in the menu and serves them.

The customer, as the Client code, orders the items and does not see how the items are prepared.

The following sample application depicts one of the ways to implement the Factory design pattern in C#.


Microsoft Visual C# 2005 Express Edition

Define the Interface

Add the new Windows Application project (with the name as FactoryDesignPattern).  Then add an interface class as IBase and paste the following code in it. This interface is defined for creating objects.

Listing 4

interface IBase
  string Perform();

Implement the Interface

Listing 5

class Algorithm1: IBase
  public string Perform()
    return "Algorithm1 Performed";
class Algorithm2: IBase
  public string Perform()
    return "Algorithm2 Performed";
class Algorithm3: IBase
  public string Perform()
    return "Algorithm3 Performed";

In Listing 5, the three classes Algorithm1, Algorithm2 and Algorithm3 are defined which implements the IBase interface (refer to Listing 4).

Define the Factory Class

First, define the Factory class.  This class is responsible for instantiating the required object and returning it to the client.  Once the object is returned, the client code will call the object methods without knowing how these objects methods are implemented.  This provides the encapsulation mechanism.

Listing 6

class Factory
  public IBase GetObject(int AlgorithmType)
    IBase objbase = null;
    switch (AlgorithmType)
      case 1:
        objbase = new Algorithm1();
      case 2:
        objbase = new Algorithm2();
      case 3:
        objbase = new Algorithm3();
        throw new Exception("Unknown Object");
    return objbase;

In the above listing, the factory class has one method, GetObject, which accepts one parameter. Based on the parameter value, one of the three IBase implementations will be returned.  The client class is responsible for choosing which Algorithm it would like to use.

If we wished to extend the factory to dynamically introduce new Algorithms, simply add another case statement in the above code with the new Algorithm object.

Create the Client Application

Add the form to the Windows Applications project and then add the button btnClient.  To this button, add the below code.

Listing 7

private void btnClient_Click(object sender,EventArgs e)
    Factory objfactory = new Factory();
    IBase objBase = objfactory.GetObject(2);
    objBase = objfactory.GetObject(3);
  catch (Exception objex)

In Listing 7, first the Factory object is created which decides the object it should return.  Then a parameter value of "2" is passed to the Getobject method of the Factory object which returns the Algorithm2 object.  This object then executes the Perform method of the Algorithm2 class.

Next, another parameter value of "3" is passed to the Getobject method of the Factory object, this time the Perform method of the Algorithm3 class is executed.

Now run the application and click the button Client on the form, after which the following messages will be displayed.

Figure 1


This Windows application illustrates how a client would use the factory class to create an instance of the desired Algorithm class.

This is a simple demonstration of the Factory design pattern.


In this article, we have seen how to hide the complex object implementation from the client by encapsulating it in the factory class.  This also provides reusable components.

Factory patterns are used extensively in building frameworks and they are implemented by the users of the Framework.

If you try to explore .NET Framework, you will find many instances of the Factory pattern implementations in it.


[Download Sample]



Factory pattern provides flexibility and reusability by using a specialized object which creates other objects in a significant manner.  This results in designing a flexible system which can withstand the changing requirements.

User Comments

Title: Superb Article   
Name: Kishor Thakur
Date: 2011-12-01 3:00:27 AM
I surfed net for this topic, but tired by reading the information about this. Still not able to grasp. But after reading above article, My funda is clear. Thanks Patil for such good information.


Kishor Thakur
Title: Where is the article   
Name: Soumya
Date: 2011-11-18 11:44:29 PM
Only definition is there.Where is the entire article.
Title: Mr.   
Name: Gaurav Verma
Date: 2011-09-07 6:15:48 AM
Good Article....Thnx buddy
Title: Mr   
Name: kashave kumar
Date: 2011-02-26 10:42:06 AM
Very good article to understand factory design pattern
Title: Nice Article   
Name: Smith
Date: 2011-01-20 6:51:22 AM
I came across a good article that elaborates more about the factory pattern
Title: Good One   
Name: Murali krishna
Date: 2010-12-29 6:28:02 AM
Very good and simple example,helps beginners to under stand very well...
Title: Mr.   
Name: Giridhari
Date: 2010-12-13 8:13:02 AM
Very nice article on factory pattern. Understandable by any one.
Thnx a lot.
Title: Superb   
Name: Milind kshirsagar
Date: 2010-06-11 8:56:49 AM
Good sample
Use interface or abstract class both are same.
Title: Not a fatory pattern   
Name: Chandra Kumar Gupta
Date: 2010-04-29 9:33:17 AM
In this method
public IBase GetObject(int AlgorithmType)
if we had to add another algorithm say algorithm5 ,how can i add, if i dont have any code.

One basic rule of programming is that
Code should be close to modification but open to extension.

so the proper example of factory pattern is given in below link
Title: Superb   
Name: Shankar
Date: 2010-04-14 3:26:55 AM
Apect way of explaining the factory method,:)
Title: Mr   
Name: Srinivasan
Date: 2010-03-31 5:18:43 AM
Simply Superb.. After a long hunt..I got the concept of Factory Pattern.. Thanks
Title: Mr.   
Name: Ashutosh
Date: 2010-03-26 1:45:13 PM
Very Nice Example ...
Title: Mr.   
Name: Neil
Date: 2010-03-23 4:53:32 AM
Good One ...Really nice example to explain in sweet N simple way.Keep it up.
Title: Mr.   
Name: Anand Gupta
Date: 2010-02-02 5:36:01 AM
Nice Article for beginners.Thank u very much.
Title: Good One   
Name: Sourabh
Date: 2010-01-25 5:06:00 AM
Nice Article
Title: Awesome that to very basic way to teach to beginners   
Name: Anu
Date: 2010-01-20 11:18:47 AM
Awesome link ....Finallyy I got something what I was looking for ..very basic to taught this topic..Thanx
Title: Nice article.Important too   
Name: Sumit Thapar
Date: 2009-11-18 5:08:29 AM
the example is really interesting and helpful.keep posting new articles. thank you.
Title: Helps to understand the concept   
Name: Mithun
Date: 2009-07-10 7:09:54 AM
the example really helped to understand the concept. keep the good work by posting many nice articles.
Title: Mr   
Name: Kalyan
Date: 2009-05-11 3:56:54 PM
Good article. More about basics of this pattern can be found here
Title: Helps to understand the concept   
Name: vinayak jogade
Date: 2009-02-02 5:48:52 AM
The example given in the artical helps to understand Factory pattern conceptually.
Title: Good job   
Name: Azi
Date: 2008-12-21 10:00:04 PM
completely understandable. Thx
Title: Design Pattern   
Name: Manish
Date: 2008-09-16 4:42:59 AM
If anyone have simple example of Abstract factory and factory pattern please mail me at
Title: Nice one   
Name: Vivek
Date: 2008-06-04 7:31:58 AM
Luv the way of explanation, please spend some more time and write some examples for other patterns as well.
Title: Simple and understandable   
Name: nutty
Date: 2008-05-28 6:30:09 AM
Very good and simple example...thanks for using your time writing this example
Title: Nice Example   
Name: Ankit Goel
Date: 2008-04-12 9:35:04 AM
Simple examples to understand complicated pattern
Title: Good one   
Name: Mamatha
Date: 2008-03-12 7:20:30 AM
Interesting Easy to understand. Nice article
Title: Simple and To the point   
Name: Manish Gupta
Date: 2008-01-17 2:14:47 AM
Really Good artical.
The best thing is that it has given a real life example.
Title: good article   
Name: sam
Date: 2008-01-16 3:02:37 PM
Please write some more article with Design Patterns using C#, will be helpful to many
Title: simple and neat   
Name: Raji
Date: 2007-12-11 2:20:25 AM
Nice article!.I understood more clearly about Factory pattern mainly becoz of the 'Restaurant' example.
Title: Factory Design Pattern   
Name: Biju K.R
Date: 2007-10-15 2:22:42 AM
Excellant...Always start with simple....Anbody will understand what is factory pattern after reading this beautiful article
Title: Superb   
Name: Pankaj Sharma
Date: 2007-10-12 4:54:18 PM
Very good example to get the basic knowledge. Keep it up Patil.
Title: Working with Factory Design Pattern using C#   
Name: Vishal Kumar Patil
Date: 2007-10-04 2:33:53 PM
This was wonderful article. I almost pulled my hair understanding Class Factory funda.. and Mr Patil had explained in easiest way. Thank you sir.

Raj M
Title: Mutliple database connection   
Name: Gopal
Date: 2007-05-23 6:35:44 AM
This is good. I connect sql and also oracle with out changing my code in ASP.NET. Is there any way i can use factory classes to handle such situation.
Title: prog   
Name: Sri
Date: 2007-02-08 10:30:54 AM
Small and very clear example. Thanks
Title: Nice Article   
Name: Marcelo
Date: 2007-01-25 3:15:18 AM
Very nicely explained. Good one !!
Title: Jason   
Name: Jason
Date: 2006-08-29 10:31:28 PM
Very good simple and to the point
Title: Found it   
Name: Redslash
Date: 2006-07-14 5:31:19 AM
nvrm found the sollution i was looking for
in case anybody needs:

public static object factory(String name)
Assembly asse = Assembly.GetEntryAssembly();

Type t = asse.GetType(asse.GetName().Name + "." + name, true, false);
if (t != null)
ConstructorInfo ci = t.GetConstructor(new Type[] { });
if (ci != null)
return ci.Invoke(new object[0]);
return null;

ofc u can also add the assembly to the method: factory(Assembly asse, String name) to gain even more controll
Title: Real factory like in java?   
Name: Redslash
Date: 2006-07-14 4:38:23 AM
is there a way to make a real factory (create object with default constructor by name) like java has?

i need something to dynamically create objects from data and to not want to define a very big list in a switch

in java:
public static Object factory(String name)
Class c = Class.forName(name);
return c.newInstance();
catch (Exception e)
System.out.println("Can't make a " + e);
return null;

(which rocks ^^)
Title: Good article   
Name: Vikram
Date: 2006-06-27 1:30:59 AM
Very good article .. written in a very simple language and makes it very easy to understand the complex topic..
Title: Good one   
Name: Baljeet
Date: 2006-04-27 4:03:54 AM
Good article for understanding

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-06-17 6:54:26 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search