Click here to Skip to main content
Licence CPOL
First Posted 10 Feb 2012
Views 3,850
Downloads 82
Bookmarked 11 times

Understanding and Implementing Factory Pattern in C#

By | 10 Feb 2012 | Article
This article aims at understanding the Factory Method and a basic implementation of Factory method in C#.

Introduction

This article aims at understanding the Factory Method and a basic implementation of Factory method in C#.

Background

There are many scenarios when a class needs to create several objects. The class can do so freely but it has to know about each and every class. The idea of factory method is to have the classes ability to create other classes without them knowing about all the possible classes that exists. This gives us extensibility. With factory method, we get the possibility of creating, maintaining and manipulating a collection of different objects that have some common characteristics. The main use of this method is in classes that manage a lot of objects like Document Manager, Control manager, Facility Manager.

GOF defines factory method as "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses".

Using the Code

Let us now look at the class diagram for Factory Pattern (Reference: GoF Design Patterns):


Let us try to see what each of these classes represents:

  • Product: defines the interface of objects the factory method creates
  • ConcreteProduct: implements the Product interface
  • Creator: declares the factory method, which returns an object of type Product.
  • ConcreteCreator: overrides the factory method to return an instance of a ConcreteProduct

Now what we have tried to do in our small exercise is that we have created a system that will manage the receivable for different type of employees, i.e., Manager, Engineer etc. so if we try to map the above mentioned classes with our little program, the hierarchy can be represented as:

my factory pattern

Creating the Abstract Product

abstract class AItems
{
    //This is just to facilitate testing of our application.
    public override string ToString()
    {
        return this.GetType().Name;
    }
}

Creating the Concrete Products

class Car : AItems { }
class CellPhone : AItems    { }
class Computer : AItems    {    }
class LapTop : AItems    {   }
class MotorBike : AItems    {  }
class EntertainmentAllowance : AItems  { }
class TravelAllowance : AItems  { }
class Salary : AItems   {  }
class Incentives : AItems  {  }

Creating the Abstract Creator

abstract class AEmployee
{
    List<AItems> benefits;

    public AEmployee()
    {
        benefits = new List<AItems>();
    }

    public void AddBenefit(AItems ben)
    {
        benefits.Add(ben);
    }

    public void PrintBenefits()
    {
        foreach (AItems a in benefits)
        {
            Console.WriteLine(a.ToString());
        }
    }

    public override string ToString()
    {
        return this.GetType().Name;
    }
}

Creating the Concrete Creators

class Manager : AEmployee
{
    public Manager()
    {
        AddBenefit(new Car());
        AddBenefit(new CellPhone());
        AddBenefit(new LapTop());
        AddBenefit(new EntertainmentAllowance());
        AddBenefit(new TravelAllowance());
        AddBenefit(new Salary());
        AddBenefit(new Incentives());
    }
}

class Engineer : AEmployee
{
    public Engineer()
    {
        AddBenefit(new Computer());
        AddBenefit(new MotorBike());
        AddBenefit(new TravelAllowance());
        AddBenefit(new Salary());
    }
}

Testing the Application

static void Main(string[] args)
{
    AEmployee man = new Manager();
    Console.WriteLine("Receivables for " + man.ToString() + ": \n");
    man.PrintBenefits();

    Console.ReadLine();

    man = new Engineer();
    Console.WriteLine("Receivables for " + man.ToString() + ": \n");
    man.PrintBenefits();

    Console.ReadLine();
}

Points of Interest

This article covers the basics of Factory Method and provides a basic implementation in C#. Perhaps it is not very useful and exciting for programming gurus here, but it sure is a good learning for a beginner like me.

History

  • 10 Feb, 2012: Simple and rudimentary implementation of Factory method in C#

License

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

About the Author

Rahul Rajat Singh

Software Developer

India India

Member

I am into Software Development since 2005. I have experience in developing Multimedia applications(Audio & Video Playback), Small 3D games using native(C++) and Managed(C#) Languages, Windows Form Applications using C#, Windows Applications using C++/MFC, e-commerce/e-governance Portals, Content Management Systems and Data driven websites.
 
My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems.
 
My skill Set: C/C++, C#, ASP.NET, ADO.NET, JavaScript, SQL Server, Design Patterns

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 PinmemberSledgeHammer017:37 11 Feb '12  
GeneralMy vote of 1 PinmemberDean Oliver22:19 10 Feb '12  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 10 Feb 2012
Article Copyright 2012 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid