Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming

Factory Method Pattern

4.27/5 (41 votes)
19 Apr 2013CPOL4 min read 165K   1.2K  
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)