Click here to Skip to main content
15,885,141 members
Articles / Programming Languages / C#
Tip/Trick

Factory Pattern Example in C#

Rate me:
Please Sign up or sign in to vote.
4.60/5 (44 votes)
2 Mar 2014CPOL2 min read 247.6K   2.4K   29   25
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.
    C#
    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:
    C#
    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:
    C#
    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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Linkedin profile: http://www.linkedin.com/profile/view?id=241442098

Comments and Discussions

 
GeneralEssence used can misguide people Pin
v2.4ever16-Apr-18 21:32
v2.4ever16-Apr-18 21:32 
QuestionNice article for newbie's Pin
VinayR@J27-May-16 0:35
professionalVinayR@J27-May-16 0:35 
AnswerRe: Nice article for newbie's Pin
Vipin_Arora28-May-16 21:12
Vipin_Arora28-May-16 21:12 
PraiseThanks for the example Pin
colbrand13-Mar-16 19:40
colbrand13-Mar-16 19:40 
QuestionAbtract factory Pin
Member 330671019-Oct-15 3:56
Member 330671019-Oct-15 3:56 
AnswerRe: Abtract factory Pin
Vipin_Arora25-Oct-15 20:33
Vipin_Arora25-Oct-15 20:33 
GeneralMy vote of 1 Pin
Aditya Magotra27-Dec-14 4:37
Aditya Magotra27-Dec-14 4:37 
GeneralRe: My vote of 1 Pin
Vipin_Arora27-Dec-14 5:33
Vipin_Arora27-Dec-14 5:33 
GeneralRe: My vote of 1 Pin
PIEBALDconsult27-Dec-14 5:44
mvePIEBALDconsult27-Dec-14 5:44 
GeneralRe: My vote of 1 Pin
Vipin_Arora27-Dec-14 5:58
Vipin_Arora27-Dec-14 5:58 
GeneralRe: My vote of 1 Pin
Aditya Magotra27-Dec-14 7:42
Aditya Magotra27-Dec-14 7:42 
GeneralRe: My vote of 1 Pin
Vipin_Arora27-Dec-14 17:49
Vipin_Arora27-Dec-14 17:49 
GeneralRe: My vote of 1 Pin
Member 1096340329-Jun-15 21:49
Member 1096340329-Jun-15 21:49 
QuestionViolation of Solids (OCP) Pin
Aditya Magotra27-Dec-14 4:21
Aditya Magotra27-Dec-14 4:21 
AnswerMessage Closed Pin
27-Dec-14 4:23
Vipin_Arora27-Dec-14 4:23 
GeneralRe: Violation of Solids (OCP) Pin
Aditya Magotra27-Dec-14 4:31
Aditya Magotra27-Dec-14 4:31 
GeneralMy vote of 1 Pin
PaperTape3-Dec-14 14:10
professionalPaperTape3-Dec-14 14:10 
GeneralRe: My vote of 1 Pin
Vipin_Arora3-Dec-14 21:42
Vipin_Arora3-Dec-14 21:42 
GeneralRe: My vote of 1 Pin
PIEBALDconsult27-Dec-14 5:47
mvePIEBALDconsult27-Dec-14 5:47 
GeneralRe: My vote of 1 Pin
Vipin_Arora27-Dec-14 5:56
Vipin_Arora27-Dec-14 5:56 
GeneralMy vote of 4 Pin
livewire#138-Sep-14 16:52
livewire#138-Sep-14 16:52 
Good job, simplest explanation...........
GeneralRe: My vote of 4 Pin
Vipin_Arora29-Apr-15 19:47
Vipin_Arora29-Apr-15 19:47 
GeneralMessage Closed Pin
3-Mar-14 1:23
professionalPBGuy3-Mar-14 1:23 
GeneralRe: My vote of 1 Pin
Klaus Luedenscheidt3-Mar-14 19:39
Klaus Luedenscheidt3-Mar-14 19:39 
GeneralRe: My vote of 1 Pin
Vipin_Arora3-Mar-14 21:08
Vipin_Arora3-Mar-14 21:08 

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

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