Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Factory Pattern Example in C#

0.00/5 (No votes)
2 Mar 2014 1  
This tip is about how to implement factory design pattern

Introduction

This tip is about how to implement factory design pattern.

Background

Design patterns are general reusable solutions to common problems that occurred in software designing. There are broadly 3 categories of design patterns, i.e., Creational, Behavioral and Structural.

Now, Factory Design Pattern falls under the category of creational design pattern.
It deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to sub classes."

(Source: Factory method pattern[^])

Where to Use?

It would be tedious when the client needs to specify the class name while creating the objects. So, to resolve this problem, we can use Factory pattern. It provides the client a simple way to create the object. The example below will elaborate the factory pattern in detail.

Using the Code

Here is the step by step procedure to create an application with Factory Pattern:

  1. Create a new Windows project (say: ProFactoryPattern).
  2. Add a ComboBox (name it cmbSelect) and one Label (for displaying the Result (name it lblResult)) as shown below:

  3. Add the below interface and two classes implement this interface. Please note that both classes have the same methods.
    interface IGet
    {
        string ConC(string s1, string s2);
    }
    
    class clsFirst : IGet
    {
        public string ConC(string s1, string s2)
        {
            string Final = "From First: " + s1+" and " + s2;
            return Final;
        }
    }
    
    class clsSecond : IGet
    {
        public string ConC(string s1, string s2)
        {
            string Final = "From Second: " + s1 + " and " + s2;
            return Final;
        }
    } 
  4. Next, add the factory class, in which conditions are there to create the objects. Method in this class basically decides object of class to be created, as shown below:
    class clsFactory
    {
        static public IGet CreateandReturnObj(int cChoice)
        {
            IGet ObjSelector = null;
    
            switch (cChoice)
            {
                case 1:
                    ObjSelector = new clsFirst();
                    break;
                case 2:
                    ObjSelector = new clsSecond();
                    break;
                default:
                    ObjSelector = new clsFirst();
                    break;
            }
            return ObjSelector;
    
        }
    }
  5. Finally, the client code looks like shown below. In this, the client does not bother about the classes and class name and does not worry if any new class will be added:
    private void cmbSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
        IGet ObjIntrface = null;
        ObjIntrface = clsFactory.CreateandReturnObj(cmbSelect.SelectedIndex + 1);
        string res = ObjIntrface.ConC("First", "Second");
        lblResult.Text = res;
    }
  6. Now the output will be:

    If 1 will be selected, then object of clsFirst will be created and in case of 2, clsSecond will be created:

Points of Interest

Now consider, if we have to add one more class (say: clsThird) and we want to add one more case in switch condition (under class: CreateandReturnObj), then client code will not change. Also, you can get the input from config.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here