Click here to Skip to main content
Click here to Skip to main content
Go to top

Factory Method Pattern

, 19 Apr 2013
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 Desme Bangladesh
Bangladesh Bangladesh
I have completed my Undergraduate from Khulna University of Engineering in Computer Science & Engineering. Now i am working as a Software Engineer at desme-Bangladesh on ASP.NET. I really love this technology and like to build my career with this only.
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 1 Pinmembertayyabakram29-May-13 3:02 
GeneralRe: My vote of 1 Pinprofessionaldpalash29-May-13 7:53 
GeneralMy vote of 5 PinmemberMihai MOGA10-May-13 18:40 
GeneralRe: My vote of 5 Pinprofessionaldpalash11-May-13 1:18 
GeneralMy vote of 2 [modified] PinmentorKeith Barrow7-May-13 22:44 
GeneralRe: My vote of 2 Pinprofessionaldpalash8-May-13 5:08 
GeneralRe: My vote of 2 PinmentorKeith Barrow8-May-13 5:15 
GeneralRe: My vote of 2 Pinprofessionaldpalash8-May-13 5:19 
GeneralMy vote of 4 PinmemberTridip Bhattacharjee20-Apr-13 8:01 
GeneralRe: My vote of 4 Pinprofessionaldpalash20-Apr-13 9:04 
GeneralMy vote of 2 PinmemberPaulo Zemek20-Apr-13 5:03 
GeneralRe: My vote of 2 Pinprofessionaldpalash20-Apr-13 9:18 
GeneralRe: My vote of 2 PinmemberFatCatProgrammer22-Apr-13 8:33 
GeneralMessage Removed Pinprofessionaldpalash22-Apr-13 10:58 
GeneralRe: My vote of 2 PinmemberFatCatProgrammer22-Apr-13 15:14 
GeneralRe: My vote of 2 Pinprofessionaldpalash22-Apr-13 21:43 
QuestionStill incorrect. PinmemberPaulo Zemek20-Apr-13 5:02 
AnswerRe: Still incorrect. Pinprofessionaldpalash20-Apr-13 9:48 
QuestionThe factory pattern is pretty PinmemberJörgen Sigvardsson20-Apr-13 1:58 
AnswerRe: The factory pattern is pretty Pinprofessionaldpalash20-Apr-13 9:21 
GeneralMy vote of 5 PinmemberMember 829355719-Apr-13 2:24 
GeneralRe: My vote of 5 Pinprofessionaldpalash19-Apr-13 4:49 
QuestionIncorrect!! PinmemberFatCatProgrammer18-Apr-13 4:16 
AnswerRe: Incorrect!! Pinprofessionaldpalash18-Apr-13 7:35 
GeneralRe: Incorrect!! PinmemberFatCatProgrammer18-Apr-13 16:23 
GeneralRe: Incorrect!! Pinprofessionaldpalash18-Apr-13 21:46 
GeneralRe: Incorrect!! PinmemberFatCatProgrammer19-Apr-13 5:46 
GeneralRe: Incorrect!! Pinprofessionaldpalash19-Apr-13 9:33 
GeneralRe: Incorrect!! [modified] PinmemberPaulo Zemek19-Apr-13 10:00 
GeneralRe: Incorrect!! Pinprofessionaldpalash19-Apr-13 11:06 
GeneralRe: Incorrect!! PinmemberPaulo Zemek19-Apr-13 17:32 
GeneralRe: Incorrect!! PinmemberFatCatProgrammer21-Apr-13 16:40 
GeneralRe: Incorrect!! PinmemberPaulo Zemek22-Apr-13 1:31 
QuestionRe Pinprofessionalsisirp8816-Apr-13 21:42 
AnswerRe: Re Pinprofessionaldpalash16-Apr-13 23:23 
GeneralReally good article PinprofessionalAmogh Natu16-Apr-13 21:01 
GeneralRe: Really good article Pinprofessionaldpalash16-Apr-13 23:22 
GeneralMy vote of 5 PinmemberSridhar Patnayak16-Apr-13 18:35 
GeneralMy vote of 5 PinmemberRobert Green16-Apr-13 7:40 
GeneralRe: My vote of 5 Pinprofessionaldpalash16-Apr-13 8:53 
GeneralMy vote of 5 Pinmembershijokg15-Apr-13 19:44 
GeneralRe: My vote of 5 Pinprofessionaldpalash15-Apr-13 22:09 
GeneralMy vote of 4 PinmemberMasked Dev10-Apr-13 6:24 
GeneralRe: My vote of 4 Pinprofessionaldpalash10-Apr-13 8:16 
QuestionVery nice article; please correct some minor typos PinmemberBrian C Hart10-Apr-13 5:54 
AnswerRe: Very nice article; please correct some minor typos PinmemberMasked Dev10-Apr-13 6:23 
GeneralRe: Very nice article; please correct some minor typos Pinprofessionaldpalash16-Apr-13 23:31 
AnswerRe: Very nice article; please correct some minor typos Pinprofessionaldpalash16-Apr-13 23:29 
QuestionYour effort is much appreciated. PinmemberPetr Kohout10-Apr-13 1:53 
AnswerRe: Your effort is much appreciated. PinmentorKeith Barrow7-May-13 22:53 

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