Time for a factory pattern

I've finally been getting some solid C++ development time in over the holidays and just the other day I got around to implementing a Factory design pattern object for the Radman Games library. For those not in the know a Factory is a pattern that eases creation of many similar objects. Essentially it allows you to ask for a certain type of object by name and have it constructed and returned to you without having to know how the construction takes place.

An example of this would be a MeshFactory, which is for creating game objects. There are possibly hundreds of meshes to choose from and each needs to be constructed from disk data or possibly specified procedurally. A Factory allows you to request any particular mesh with the following simple syntax:

Mesh* mesh = factory.create("ParticularMesh");

Kinda seems a bit like magic huh? Well there is an important step that I glossed over, which is that; for each object type you want to be able to create the Factory must be given the means of constructing that object type. This really isn't much of a problem and is in fact one of the reasons that the Factory is such a flexible and useful pattern. The solution is to provide the factory with an executable object that returns an object of the type required. To facilitate this the Factory has a register method in its interface, which is used like so:

Mesh* createHexagon()
{
  // return configured mesh 
}

meshFactory.registerCreator("Hexagon", &createHexagon);

// then to get a hexagon you do
Mesh* hexagon = meshFactory.create("Hexagon");

Things can get more complicated with Factories but this is the basic concept in a nutshell. The Factory that I have written for my library is templated to make it generic but it still has just these two as it's interface.

void registerCreator(<objectID>, <creatorMethod>);
Object* create(<objectID>);

As it turns out my driver for writing a Factory was to ease the creation of a number of procedurally generated meshes to be used in the demo I'm building ;). You can get the source code for my GenericFactory below if you're interested in taking a look. As always feedback is more than welcome and I'm happy to help if you are having trouble making the code work. Till next time.

Get the GenericFactory source code

Leave a Comment