The Problem
In object oriented programming, it is very common to have a scenario where a large
number of classes share the same base class and the particular implementation needs
to be created at runtime based on some specific parameters, for example a class name
held in a string.
Standard C++ does not provide the same type of reflection mechanism that other languages
use to achieve this, such as C# :
System.Reflection.Assembly.GetExecutingAssembly()
.CreateInstance(string className)
or in Java:
Class.forName(className).getConstructor(String.class).newInstance(arg);
However, C++ does not allow us to do such things; we have to come up with another solution.
The basic pattern, or set of patterns, that help us achieve this are factory patterns.
A Simple Solution
The Base Class
Our base class is defined as an abstract class as follows:
#ifndef CPPFACTORY_MYBASECLASS_H
#define CPPFACTORY_MYBASECLASS_H
class MyBaseClass
{
public:
virtual void doSomething() = 0;
};
#endif // CPPFACTORY_MYBASECLASS_H
The Factory Class
A factory method can then be defined as a static method that can be used to create
instances of MyBaseClass
. We could define this as a static method on
MyBaseClass
itself, although it is generally good practice in object oriented development that a class
serves a single purpose. Therefore, lets create a factory class:
#ifndef CPPFACTORY_MYFACTORY_H
#define CPPFACTORY_MYFACTORY_H
#include "MyBaseClass.h"
#include <memory>
#include <string>
using namespace std;
class MyFactory
{
public:
static shared_ptr<MyBaseClass> CreateInstance(string name);
};
#endif // CPPFACTORY_MYFACTORY_H
The factory method is expected to create an instance of a class named name that is derived
from MyBaseClass
and return it as a shared pointer, as it will relinquish ownership
of the object to the caller.
We shall return to the implementation of the method shortly.
Some Derived Classes
So lets implement a couple of derived classes:
#ifndef CPPFACTORY_DERIVEDCLASSONE_H
#define CPPFACTORY_DERIVEDCLASSONE_H
#include "MyBaseClass.h"
#include <iostream>
using namespace std;
class DerivedClassOne : public MyBaseClass
{
public:
DerivedClassOne(){};
virtual ~DerivedClassOne(){};
virtual void doSomething() { cout << "I am class one" << endl; }
};
#endif // CPPFACTORY_DERIVEDCLASSONE_H
and
#ifndef CPPFACTORY_DERIVEDCLASSTWO_H
#define CPPFACTORY_DERIVEDCLASSTWO_H
#include "MyBaseClass.h"
#include <iostream>
using namespace std;
class DerivedClassTwo : public MyBaseClass
{
public:
DerivedClassTwo(){};
virtual ~DerivedClassTwo(){};
virtual void doSomething() { cout << "I am class two" << endl; }
};
#endif // CPPFACTORY_DERIVEDCLASSTWO_H
A First Attempt at the Factory Method
A simple solution to the implementation of the factory method would be something like
this:
#include "MyFactorySimple.h"
#include "DerivedClassOne.h"
#include "DerivedClassTwo.h"
shared_ptr<MyBaseClass> MyFactory::CreateInstance(string name)
{
MyBaseClass * instance = nullptr;
if(name == "one")
instance = new DerivedClassOne();
if(name == "two")
instance = new DerivedClassTwo();
if(instance != nullptr)
return std::shared_ptr<MyBaseClass>(instance);
else
return nullptr;
}
The factory determines which concrete class to create and has knowledge of every class
via the class headers.
Running the application
A simple main function is now needed so that we can test our implementation:
#include "MyFactorySimple.h"
int main(int argc, char** argv)
{
auto instanceOne = MyFactory::CreateInstance("one");
auto instanceTwo = MyFactory::CreateInstance("two");
instanceOne->doSomething();
instanceTwo->doSomething();
return 0;
}
A Visual Studio Project (SimpleFactory.vcxproj) is included with the source code accompanying
this article which can be built and run giving the following output:
I am class one
I am class two
Problems with the Simple Solution
On the surface this looks like a good solution and it possibly is in some cases. However,
what happens if we have a lot of classes deriving from MyBaseClass
? We keep having
to add the includes and the compare – construct code.
The problem now is that the factory has an explicit dependency on all the derived
classes, which is not ideal. We need to come up with a better solution; one that removes
the need for constantly adding to the MyFactory::Create
. This is where the idea of a
registry of factory methods can help us.
A Revised Factory Class
One of our main objectives is to remove the dependencies on the derived classes from
the factory. However, we still need to allow the factory to trigger the creation of instances.
One way to do this is for the main factory class to maintain a registry of factory
functions that can be defined elsewhere. When the factory class needs to create an instance
of a derived class, it can look up the factory function in this registry. The registry
is defined as follows:
map<string, function<MyBaseClass*(void)>> factoryFunctionRegistry;
It is a map, keyed on a string with values as functions that return a pointer to an instance
of a class based on MyBaseClass
.
We can then have a method on MyFactory
which can add a factory function to the registry:
void MyFactory::RegisterFactoryFunction(string name,
function<MyBaseClass*(void)> classFactoryFunction)
{
factoryFunctionRegistry[name] = classFactoryFunction;
}
The Create
method can then be changed as follows:
shared_ptr<MyBaseClass> MyFactory::Create(string name)
{
MyBaseClass * instance = nullptr;
auto it = factoryFunctionRegistry.find(name);
if(it != factoryFunctionRegistry.end())
instance = it->second();
if(instance != nullptr)
return std::shared_ptr<MyBaseClass>(instance);
else
return nullptr;
}
So how do we go about registering the classes in a way that keeps dependencies to a
minimum? We cannot easily have instances of the derived classes register themselves
as we can’t create instances without the class being registered. The fact that we need the
class registered, not the object gives us a hint that we may need some static variables
or members to do this.
I stress that the way I am going to do this may not be the best in all scenarios. I am deeply
suspicious of static variables and members, as static initialization can be a minefield.
However, I will press on, as the solution serves the purpose of this example and it is up
to the reader to determine whether a solution they use needs to follow different rules
and design.
Firstly we define a method on MyFactory
to obtain the singleton instance:
MyFactory * MyFactory::Instance()
{
static MyFactory factory;
return &factory;
}
We cannot call the following from the global context:
MyFactory::Instance()->RegisterFactoryFunction(name, classFactoryFunction);
I have therefore created a Registrar class that will do the call for us in its constructor:
class Registrar {
public:
Registrar(string className, function<MyBaseClass*(void)> classFactoryFunction);
};
...
Registrar::Registrar(string name, function<MyBaseClass*(void)> classFactoryFunction)
{
MyFactory::Instance()->RegisterFactoryFunction(name, classFactoryFunction);
}
Once we have this, we can create static instances of this in the source files of the derived
classes as follows (DerivedClassOne
):
static Registrar registrar("one",
[](void) -> MyBaseClass * { return new DervedClassOne();});
As it turns out, this code can be duplicated in all derived classes so a quick pre processor
define as follows:
#define REGISTER_CLASS(NAME, TYPE) \
static Registrar registrar(NAME, \
[](void) -> MyBaseClass * { return new TYPE();});
This uses the new C++ lambda support to declare anonymous functions. We then
only need add the following to each derived class source file:
REGISTER_CLASS("one", DerivedClassOne);
Update 25th January 2013
We Can Do Better …
Although the #define solution provides a neat implementation we could probably do this in a bit more of a C++ style by converting the Registrar class into a template class as follows:
template<class T>
class Registrar {
public:
Registrar(string className)
{
MyFactory::Instance()->RegisterFactoryFunction(name,
[](void) -> MyBaseClass * { return new T();});
}
};
And now we can replace the use of the macro by
static Registrar<DerivedClassOne> registrar("one");
We now have a function registry based factory class defined and the main function can
now be slightly modified as follows:
#include "MyFactory.h"
int main(int argc, char** argv)
{
auto instanceOne = MyFactory::Instance()->Create("one");
auto instanceTwo = MyFactory::Instance()->Create("two");
instanceOne->doSomething();
instanceTwo->doSomething();
return 0;
}
We can now build and run the project and get the following output:
I am class one
I am class two
References: