Click here to Skip to main content
11,643,493 members (74,911 online)
Click here to Skip to main content

Factory Method Pattern

, 19 Apr 2013 CPOL 56K 707 54
Rate this:
Please Sign up or sign in to vote.
Easy way to understand Factory Method Pattern

Introduction  

In this article i have tried to explain the Concept of factory method pattern and the way of implementing factory method pattern. 

Background 

Before learning Factory Method Pattern, i just want to share a little about "Gang of Four" to which the Factory Method pattern belongs.  

Who are the Gang of Four? 

The Gang of Four are the authors of the book, "Design Patterns: Elements of Reusable Object-Oriented Software". This important book describes various development techniques and pitfalls in addition to providing twenty-three object-oriented programming design patterns. The four authors were Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. Now we will move on to Factory Method Pattern.

Factory Method: 

Definition: “The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.”

This is the formal definition of factory method pattern. 

In my opinion to understand Factory Method Pattern easily we can say that it’s a method that provides the object of a class at run time. Now let’s understand this with a very easy example.

Suppose, we have an ice-cream factory. So the first scenario comes in mind that it makes ice-cream obviously. We can treat this as a "Factory" of our Factory Method Pattern. Say, you went to a shop to buy a chocolate ice-cream. So what do we usually do? We ask for the ice-cream, don't we? and the shopkeeper provides us the ice-cream we wanted. Here we will make a call to this Factory that will give me a chocolate ice-cream like we do at a store. And the task of this method (Factory) will be to fulfill the desired demand that a customer makes. So basically Factory Method Pattern is just a method which actually fulfills our demand of object creation at run-time.  

Now, let's have a look at the UML class diagram of Factory Method Pattern.

Now we will learn about these blocks and what actually they represent. 

  1. ConcreteCreator: Concrete classes that will create the Product. This will keep track of what Product it has created. 
  2. Product: This is the object that will be created by combining available raw materials.
  3. Creator: This is the interface for creating the actual products
Now we will implement Factory Method Pattern in our program.

First we need to understand where we want to implement this pattern and then how to implement. Let’s review the scenario of where to implement this pattern. 

Suppose we have an Ice-cream Factory. We make ice-cream of two categories (chocolate & Vanilla). We are going very well in market. Our selling rate is quite satisfactory. Now one day we got an interesting phone call from one of our customers that his boy wants something in different taste. He is boring with these two tastes. Similarly we received some more phone calls regarding this issue of changing the taste of ice-cream we make. So we called an urgent meeting and decided to create something special for our valuable customers. In meeting we have also decided to use our existing available raw materials and technologies. So obviously all we need is to change something core items that will give us a different taste and flavor but all other procedure will be same.

Here the idea of Factory Method Pattern describes that we can reuse our existing available raw materials, technologies and anything that we can use to create new items.  

In software development the available useable things are methods, properties etc.

So let’s develop software that can handle these types of requirements. This is why we should use the factory
method pattern.

In a sentence we are capable of using Factory Method Pattern where the requirements are frequently changing. Here is a simple demonstration of the above discussion.

So now let’s code to handle this. 

First of all we need a base class that will hold the basic functionality to make an ice-cream. The functionality of making ice-cream is same for different types of ice-creams but the ingredients are different. So i am going to put the basic functionality of ice-cream making in an interface and then i am going to implement that functionality for making different types of ice-creams (Products). Let’s look at the following code.

interface IIceCream
{
    string Functionality();
}
class ChocolateIceCream : IIceCream
{
    public string Functionality()
    {
        return "Chocolate Ice cream";
    }
}
class VanillaIceCream : IIceCream
{
    public string Functionality()
    {
        return "Vanilla Ice cream";
    }
}
class StrawberryIceCream : IIceCream
{
    public string Functionality()
    {
        return "Strawberry Ice cream";
    }
} 

Here IIceCream is the base interface that holds definition of the Functionality method as I have described earlier. The others are the Product classes that make individual ice-creams (Products) by implementing the definition of Functionality from the IIceCream interface. 

This is the basic structure of our program. Now we need to implement the "Factory Method", which will create the instance of our desired ice-cream at run-time. So we will create this method now.

This is how I’m going to do this.

static class Factory
{
   /// <summary>
   /// This is the Factory method
   /// </summary>
   public static IIceCream Get(int id)
   {
       switch (id)
       {
           case 0:
                return new ChocolateIceCream();
           case 1:
                return new VanillaIceCream();
           case 2:
                return new StrawberryIceCream();
           default:
                return null;
        }
   }
} 

Here Get() is the Factory Method which takes the id as a parameter from user and creates the instance of that particular class matching the case statement. The client is responsible to pass the id into this method. So this is the method we are talking all through. This is the main implementation of Factory Method Pattern.  

We just now need a client to call this method. Here is the code for client that will complete the program.

/// <summary>
/// This is the Client
/// </summary>
static void Main()
{
   for (int i = 0; i <= 3; i++)
   {
       var type = Factory.Get(i);
       if (type != null)
       {
           Console.WriteLine("This is Product : " + type.Functionality());
       }
   }
} 

Summary   

Factory method is just like regular method but when we are talking about patterns it just returns the instance of a class at run-time.

License

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

Share

About the Author

dpalash
Software Developer Cefalo
Bangladesh Bangladesh
Hi,

I am Palash Debnath. I have been working on windows technologies since 2008. I started with ASP.NET. Then I moved to Windows Form and from the last year I have been working with Windows 8 app development. My future plan is to work with Windows 10 app development as well. I have completed my Undergraduate from Khulna University of Engineering in Computer Science & Engineering. Now I am working as a Software Engineer at Cefalo on Windows 8 app development.

You may also be interested in...

Comments and Discussions

 
GeneralGuys, do not be lock on concrete realization Pin
zzfima24-Mar-15 6:02
memberzzfima24-Mar-15 6:02 
Questionmy vote is 1 Pin
Member 1081780228-Sep-14 1:56
memberMember 1081780228-Sep-14 1:56 
GeneralMy vote of 1 Pin
tayyabakram29-May-13 3:02
membertayyabakram29-May-13 3:02 
GeneralRe: My vote of 1 Pin
dpalash29-May-13 7:53
professionaldpalash29-May-13 7:53 
GeneralMy vote of 5 Pin
Mihai MOGA10-May-13 18:40
memberMihai MOGA10-May-13 18:40 
GeneralRe: My vote of 5 Pin
dpalash11-May-13 1:18
professionaldpalash11-May-13 1:18 
GeneralMy vote of 2 Pin
Keith Barrow7-May-13 22:44
mentorKeith Barrow7-May-13 22:44 
GeneralRe: My vote of 2 Pin
dpalash8-May-13 5:08
professionaldpalash8-May-13 5:08 
GeneralRe: My vote of 2 Pin
Keith Barrow8-May-13 5:15
mentorKeith Barrow8-May-13 5:15 
GeneralRe: My vote of 2 Pin
dpalash8-May-13 5:19
professionaldpalash8-May-13 5:19 
GeneralMy vote of 4 Pin
Tridip Bhattacharjee20-Apr-13 8:01
memberTridip Bhattacharjee20-Apr-13 8:01 
GeneralRe: My vote of 4 Pin
dpalash20-Apr-13 9:04
professionaldpalash20-Apr-13 9:04 
GeneralMy vote of 2 Pin
Paulo Zemek20-Apr-13 5:03
memberPaulo Zemek20-Apr-13 5:03 
GeneralRe: My vote of 2 Pin
dpalash20-Apr-13 9:18
professionaldpalash20-Apr-13 9:18 
GeneralRe: My vote of 2 Pin
FatCatProgrammer22-Apr-13 8:33
memberFatCatProgrammer22-Apr-13 8:33 
GeneralMessage Removed Pin
dpalash22-Apr-13 10:58
professionaldpalash22-Apr-13 10:58 
GeneralRe: My vote of 2 Pin
FatCatProgrammer22-Apr-13 15:14
memberFatCatProgrammer22-Apr-13 15:14 
GeneralRe: My vote of 2 Pin
dpalash22-Apr-13 21:43
professionaldpalash22-Apr-13 21:43 
QuestionStill incorrect. Pin
Paulo Zemek20-Apr-13 5:02
memberPaulo Zemek20-Apr-13 5:02 
AnswerRe: Still incorrect. Pin
dpalash20-Apr-13 9:48
professionaldpalash20-Apr-13 9:48 
QuestionThe factory pattern is pretty Pin
Jörgen Sigvardsson20-Apr-13 1:58
memberJörgen Sigvardsson20-Apr-13 1:58 
AnswerRe: The factory pattern is pretty Pin
dpalash20-Apr-13 9:21
professionaldpalash20-Apr-13 9:21 
GeneralMy vote of 5 Pin
Member 829355719-Apr-13 2:24
memberMember 829355719-Apr-13 2:24 
GeneralRe: My vote of 5 Pin
dpalash19-Apr-13 4:49
professionaldpalash19-Apr-13 4:49 
QuestionIncorrect!! Pin
FatCatProgrammer18-Apr-13 4:16
memberFatCatProgrammer18-Apr-13 4:16 
AnswerRe: Incorrect!! Pin
dpalash18-Apr-13 7:35
professionaldpalash18-Apr-13 7:35 
GeneralRe: Incorrect!! Pin
FatCatProgrammer18-Apr-13 16:23
memberFatCatProgrammer18-Apr-13 16:23 
GeneralRe: Incorrect!! Pin
dpalash18-Apr-13 21:46
professionaldpalash18-Apr-13 21:46 
GeneralRe: Incorrect!! Pin
FatCatProgrammer19-Apr-13 5:46
memberFatCatProgrammer19-Apr-13 5:46 
GeneralRe: Incorrect!! Pin
dpalash19-Apr-13 9:33
professionaldpalash19-Apr-13 9:33 
GeneralRe: Incorrect!! Pin
Paulo Zemek19-Apr-13 10:00
memberPaulo Zemek19-Apr-13 10:00 
GeneralRe: Incorrect!! Pin
dpalash19-Apr-13 11:06
professionaldpalash19-Apr-13 11:06 
GeneralRe: Incorrect!! Pin
Paulo Zemek19-Apr-13 17:32
memberPaulo Zemek19-Apr-13 17:32 
GeneralRe: Incorrect!! Pin
FatCatProgrammer21-Apr-13 16:40
memberFatCatProgrammer21-Apr-13 16:40 
GeneralRe: Incorrect!! Pin
Paulo Zemek22-Apr-13 1:31
memberPaulo Zemek22-Apr-13 1:31 
QuestionRe Pin
sisirp8816-Apr-13 21:42
professionalsisirp8816-Apr-13 21:42 
AnswerRe: Re Pin
dpalash16-Apr-13 23:23
professionaldpalash16-Apr-13 23:23 
GeneralReally good article Pin
Amogh Natu16-Apr-13 21:01
professionalAmogh Natu16-Apr-13 21:01 
GeneralRe: Really good article Pin
dpalash16-Apr-13 23:22
professionaldpalash16-Apr-13 23:22 
GeneralMy vote of 5 Pin
Sridhar Patnayak16-Apr-13 18:35
memberSridhar Patnayak16-Apr-13 18:35 
GeneralMy vote of 5 Pin
Robert Green16-Apr-13 7:40
memberRobert Green16-Apr-13 7:40 
GeneralRe: My vote of 5 Pin
dpalash16-Apr-13 8:53
professionaldpalash16-Apr-13 8:53 
GeneralMy vote of 5 Pin
shijokg15-Apr-13 19:44
membershijokg15-Apr-13 19:44 
GeneralRe: My vote of 5 Pin
dpalash15-Apr-13 22:09
professionaldpalash15-Apr-13 22:09 
GeneralMy vote of 4 Pin
Masked Dev10-Apr-13 6:24
memberMasked Dev10-Apr-13 6:24 
GeneralRe: My vote of 4 Pin
dpalash10-Apr-13 8:16
professionaldpalash10-Apr-13 8:16 
QuestionVery nice article; please correct some minor typos Pin
Brian C Hart10-Apr-13 5:54
memberBrian C Hart10-Apr-13 5:54 
AnswerRe: Very nice article; please correct some minor typos Pin
Masked Dev10-Apr-13 6:23
memberMasked Dev10-Apr-13 6:23 
GeneralRe: Very nice article; please correct some minor typos Pin
dpalash16-Apr-13 23:31
professionaldpalash16-Apr-13 23:31 
AnswerRe: Very nice article; please correct some minor typos Pin
dpalash16-Apr-13 23:29
professionaldpalash16-Apr-13 23:29 

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 | Terms of Use | Mobile
Web03 | 2.8.150731.1 | Last Updated 20 Apr 2013
Article Copyright 2013 by dpalash
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid