Factory method pattern

By | June 15, 2015

Design patterns. And that book.
I will not say anything more.

I plan to do a whole series on Design Patterns. But this is a plan not a commitment.

I will start out with the “Hello World” of design patterns: “Factory Pattern”. For the impatient, a Factory method pattern sample implementation in C++ is at the end of this post.

What trips the average Joe’s of software world is UML heavy Design pattern explainations. That is a “How”. But not “Why”.
The book does talk about “Why” but then it could have talked a bit more. Whatever.

What I will do is to talk about “Why” first. Lets take a detour.

Suppose you want to gift Roses on Valentine Day. You call up the florist and say “Roses please”. And you get a bunch of Roses.

At this point ask yourself, Do you really want to know where the Roses originated?
– Most probably not.

Does it make your life simpler? Think about it.
–  If there was no florist you might have to find where the Rose garden was.
–  When the roses are in bloom.
–  How to pick them and then create a bunch and what not.

And suppose you needed 8 such bouquets of Roses over a period of 2 days (someone is popular !!). Can you imagine going through the process 8 times?

Here the florist is playing a role of factory. He has hidden all the messy details and provides you a bouquet of roses. And makes your life simple.

Back to Software world.

In software world, it is inevitable that you will be creating objects. The question is “Where”?

You can go through the messy process of creating the object wherever you need. And some objects can be complicated to create.

Or you can have a small class (which we will creatively call Factory) which will essentially do the same thing. The class provides a method. You call that method. And inside method the object is created and then returned.
Suddenly :
– Your code is much cleaner. Messy object creation code scattered all over is now gone.
– The object creation logic is centralized in one class. If you want to change the logic, do it in that class and everywhere the object creation happens correctly as per the changed logic.

To repeat, the complexity of object creation still remains. It is just that you shifted it out to a class (which I will call Factory) and removed it from all your mainstream classes where you wanted the instance of the object. Instead you now call a method (which I am calling Create) on the Factory class object. And viola. A shining new object to play with.

This is Factory pattern. As simple as that. No UML needed (As of now).

Flavours of Factory pattern:

1 – Most common one is this. “Create” method of Factory takes a parameter which tells it what kind of object has to be returned. For example I can call it like Create(“Red”). Then it will  create a bunch of Red Roses.
2 – Create method of the Factory class will not take any parameter. It always returns same kind of object.
3 – Very simple implementation where instead of Create, the Factory is given CreateRedRose(), CreateYellowRose() and so on methods. This is also factory pattern.

So how do you go about implementing it?

1 – Create an object of Factory class.
2 – Use that object to get the instance of the class you want by calling some method of the Factory class.

It is as simple as that. Now there are multiple variations here, notably the abstract methods and what not. Do not get confused. Just remember the basics.

And how it looks like in real life?

Now it gets complicated. Fasten your seat belts.

I will try to keep it as simple as well as mainstream as possible. I expect some familiarity with C++ and concept of interfaces.

1 – You have an interface called IRose.
2 – You have an interface called IFactory.
3 – RedRose implements IRose.
4 – YellowRose implements IRose.
5 – You create an instance of the IFactory and call its Create method. Pass parameters if needed.
6 – Everytime you get the right instance as asked for.

Here is a simple C++ implementation of the same:

#include<iostream>
#include<string>
#include<cstdlib>

using namespace std;

class IRose
{
public:
	virtual string Color(void)=0;
};

class RedRose: public IRose
{
public:
	string Color(void)
	{
		return "Red";
	}
};

class YellowRose: public IRose
{
public:
	string Color(void)
	{
		return "Yellow";
	}
};

class IFactory
{
public:
	virtual IRose* Create(string type)=0; 
	//The factory create method in 90% of cases will take a parameter which 
	//determines what kind of the object the factory will return.	
};

class Factory: public IFactory
{
public:
	IRose* Create(string type)
	{
		if ("Red" == type)
			return new RedRose();

        if ("Yellow" == type)
			return new YellowRose();
		
        return NULL;
	}
};

int main()
{
	IRose* p = NULL;
	IFactory* f = NULL;

	f = new Factory();	//You have to create an INSTANCE of the factory

	p = f->Create("Red");
	cout<<"\nColor is: "<<p->Color()<<"\n";
	delete p;
	p = f->Create("Yellow");
	cout<<"\nColor is: "<<p->Color()<<"\n";
	delete p;
	return 1;
}

 

This factory method pattern example in c++ is not a professional one as such. Notably the classes will be in seperate files. But in terms of the wiring up of the classes, it is pretty close to what you will see in real world code.

This finishes the tutorial on Factory Method Pattern. A closely related pattern is Abstract Factory Pattern. That will be subject of another post. Which is now online.

One thought on “Factory method pattern

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.