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

Factory Pattern Example in C#

, 2 Mar 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

License

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

Share

About the Author

Vipin_Arora
Software Developer (Senior)
India India
Linkedin profile: http://www.linkedin.com/profile/view?id=241442098
Follow on   LinkedIn

Comments and Discussions

 
GeneralMy vote of 4 Pinmemberlivewire#138-Sep-14 16:52 
GeneralMy vote of 1 PinprofessionalPBGuy3-Mar-14 1:23 
GeneralRe: My vote of 1 PinmemberKlaus Luedenscheidt3-Mar-14 19:39 
GeneralRe: My vote of 1 PinmemberVipin_Arora3-Mar-14 21:08 

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.141022.2 | Last Updated 3 Mar 2014
Article Copyright 2014 by Vipin_Arora
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid