Factory Patterns in C++

In a nutshell, the factory design pattern enables the practitioner to create objects that share a common theme but without having to specify their exact classes. In essence the factory pattern is used to “Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.

As shown in this simple example, the factory class accomplishes the task by defining a method for creating the objects, of which the subclasses override the methods by way of polymorphism / virtual functions in order to specify the desired kinds of behaviour in the subclass methods.

#include <iostream>
#include <string>

using namespace std;  
  
class Abstract  
{  
public:  
    virtual void DoStuff() = 0;  
};  
  
class Concrete1 : public Abstract  
{  
public:  
    void DoStuff() { cout << "Hello" << endl; }  
};  
  
class Concrete2 : public Abstract  
{  
public:  
    void DoStuff() { cout << "Ola" << endl; }  
};  
  
class Factory  
{  
public:  
    Abstract* Create( string type );  
};  
  
Abstract* Factory::Create( string type )  
{  
    Abstract* ab = NULL;  
  
    if ( type == "Class 1" ) ab = new Concrete1();  
    else ab = new Concrete2();  
  
    return ab;  
}  

class Application
{
public:
	Application() {}

	void Function( std::string appType );
};

void Application::Function( std::string appType )
{
	Factory f;
	Abstract* ab = f.Create( appType );  
	ab->DoStuff();
	delete ab;
}

int main()  
{  	     
	Application application;
	application.Function( "Class 1" );
	application.Function( "" );
   
    return 0;  
} 

Giving the following output:

Hello
Ola

Leave a Reply