Featured Post

Trie implementation in C

Factory Method Design Pattern implementation in C++

What does a factory mean ? It is something which creates/manufactures some products.

Same is the job of factory design pattern. It is responsible for instantiation/creation of objects. But wait, isn't that something what constructors do ? Yes call to constructor indeed creates the object and that's exactly what a factory method does but with an additional feature of option of choosing between different constructors based on some logic.

Factory methods decide logically what constructor to call. So, instead of directly calling the constructor for a class, we call a factory method to get the object. There can be multiple derived classes from a base class. The factory method instantiates the appropriate sub-class based on the arguments passed to it and returns the base class type. This base class object can be used to access the derived class members/methods.

Blah, blah, blah... Let's get down to business and understand what it actually is and what it does.


A basic structure:

Basic structure of factory design pattern

Now let's explain it with a simple example:
Assume that we are an online Music Store . We every kind of music be it Rock, Classical, Jazz, Reggae, Techno and what not. Of course, to organize these we need categories based on different genres. Lets design this model using factory design pattern. Our base class is what we do. We provide music, so say "Music" is our base class.

Now Music can be classified into multiple categories . We for the time being assume only three.
  • Rock
  • Pop
  • Reggae
The class structure would be something like this:

Class Structure

Here Rock, Pop and Reggae are the derived classes from base class Music.

We create a factory pattern for this class structure in which we provide a factory method getMusic(genre_e genre) to the user. Using this method, one can instantiate the object of any subclass by choosing the genre.

Here genre is the logic based on which any particular subclass is instantiated. Advantage of this pattern is that outer world need not instantiate specific objects using the different sub-class constructors. It is being masked in the implementation of factory method.

Factory pattern for the class Music
Moreover if any new genre needs to be added, that can be done easily just by adding a new case in Factory method.

And now the code :

Factory Method Design Pattern implementation (C++)

 #include <iostream>
using namespace std;

enum genre_e{ROCK,POP, REGGAE, INVALID};

/*Base Class*/
class Music {
public:
 virtual void song() = 0;
};

/*Derived class Rock from Music*/
class Rock: public Music
{
public:
 void song()
 {
  cout<<"Nirvana: Smells like a teen spirit\n";
 }
};

/*Derived class Pop from Music*/
class Pop: public Music
{
public:
 void song()
 {
  cout<<"Michael Jackson: Billie Jean\n";
 }
};

/*Derived class Reggae from Music*/
class Reggae: public Music
{
public:
 void song()
 {
  cout<<"Bob Marley: No woman, No cry\n";
 }
};

/*Factory Class*/
class MusicFactory
{
public:
 /*Factory Method*/
 Music *getMusic(genre_e genre)
 {
  Music *music = NULL;

  /*Logic based on Genre*/
  switch(genre)
  {
  case ROCK:
   music = new Rock();
   break;
  case POP:
   music = new Pop();
   break;
  case REGGAE:
   music = new Reggae();
   break;
  default:
   music = NULL;
   break;
  }
  return music;
 }
};

int main()
{
 /*Create factory*/
 MusicFactory *musicFactory = new MusicFactory();

 /*Factory instantiating an object of type ROCK*/
 Music *music = musicFactory->getMusic(ROCK);

 cout<<"Song: ";
 if(music)
  music->song();
 else
  cout<<"Wrong selection dude/dudette !!";
}

Comments

  1. Is this code complete? What should we do if i have to give the input as Rock or other Genre? Please Explain

    ReplyDelete
    Replies
    1. Hi,

      I have updated the driver code to choose ROCK as the Genre. The output will be based on Rock() constructor.

      Delete
    2. Akash, you don't seem to have interest in Database as you do in Advanced Programming. I don't like this. Be careful.

      Delete
    3. This comment has been removed by the author.

      Delete
  2. I have a question.
    getMusic method return a reference object which it get after allocating memory from heap.
    which class is responsible for deleting the reference of object.

    For example:
    int main()
    {
    MusicFactory *musicFactory = new MusicFactory();
    Music *pop= musicFactory->getMusic(POP);
    {
    Music *rock= musicFactory->getMusic(ROCK);
    }
    /* my question is who and how delete the reference of ROCK object which hold rock. Now, rock is out of scope.*/

    delete musicFactory ;
    /*After executing above delete, who delete the POP object's reference which was hold by pop
    It create memory leakage issue.
    */

    }

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Please post your valuable suggestions