Click here to Skip to main content
15,881,381 members
Articles / General Programming

Factory Method Pattern

Rate me:
Please Sign up or sign in to vote.
4.27/5 (41 votes)
19 Apr 2013CPOL4 min read 154.9K   1.2K   60   77
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.
Image 1

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.

Image 2

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.

C#
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.

C#
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.

C#
/// <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)


Written By
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. Work with Windows 10 apps development as well. Now I have been working with Microsoft Azure. I have completed my Undergraduate from Khulna University of Engineering in Computer Science & Engineering. Currently working as a Senior Software Engineer at Cefalo.

Comments and Discussions

 
GeneralRe: Incorrect!! Pin
Paulo Zemek19-Apr-13 10:00
mvaPaulo 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
mvaPaulo Zemek19-Apr-13 17:32 
GeneralRe: Incorrect!! Pin
FatCatProgrammer21-Apr-13 16:40
FatCatProgrammer21-Apr-13 16:40 
GeneralRe: Incorrect!! Pin
Paulo Zemek22-Apr-13 1:31
mvaPaulo Zemek22-Apr-13 1:31 
QuestionRe Pin
Sisir Patro16-Apr-13 21:42
professionalSisir Patro16-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 
The article was really well written, neat & in simple language. You said it correctly in one of the comments that new learners should be learning old issues too. Except for small typos and grammer mistakes, the article is really helpful.
Thanks,
Amogh Natu.

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
professionalSridhar Patnayak16-Apr-13 18:35 
GeneralMy vote of 5 Pin
Robert Green16-Apr-13 7:40
Robert 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
shijokg15-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
MaskedDev10-Apr-13 6:24
professionalMaskedDev10-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
professionalBrian C Hart10-Apr-13 5:54 
AnswerRe: Very nice article; please correct some minor typos Pin
MaskedDev10-Apr-13 6:23
professionalMaskedDev10-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 
QuestionYour effort is much appreciated. Pin
Petr Kohout10-Apr-13 1:53
Petr Kohout10-Apr-13 1:53 
AnswerRe: Your effort is much appreciated. Pin
Keith Barrow7-May-13 22:53
professionalKeith Barrow7-May-13 22:53 
GeneralMy vote of 3 Pin
pates9-Apr-13 5:10
pates9-Apr-13 5:10 
GeneralRe: My vote of 3 Pin
dpalash9-Apr-13 8:05
professionaldpalash9-Apr-13 8:05 
GeneralRe: My vote of 3 Pin
pates9-Apr-13 9:03
pates9-Apr-13 9:03 

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.