This is from the book
Modern C++ Design. Generic Programming and Design Patterns Applied.
That particular section is explaining how each shape class register itself with the Class factory using the
Line shape as an example.
1. In this design the Shape factory class has a function called
1 2 3
|
// Returns 'true' if registration was successful
bool RegisterShape(int ShapeId,
CreateShapeCallback CreateFn);
| |
2. Each shape class defines for itself and ID and a non-member function that will be used to create new
objects of that shape. It will register the ID and the function with the Class Factory Object.
In the example of the Line shape - that is where the code originally posted by
n4nature comes in:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
// Implementation module for class Line
// Create an anonymous namespace
// to make the function invisible from other modules
namespace
{
Shape* CreateLine()
{
return new Line;
}
// The ID of class Line
const int LINE = 1;
const bool registered =
TheShapeFactory::Instance().RegisterShape(
LINE, CreateLine);
}
| |
3.
BUT how do we get our class registered with the Factory?
This is the part where I think
n4nature is getting confused.
We want to register our shape classes before the program starts (that is before main() is called), we do
not want to create an object of that shape in order to get registered (that would be self defeating).
What we do, is that in each cpp file we create a file scope global variable (we use the unnamed namespace to provide the file scope restriction).
In C++ gloabals and static local variables are initialised before the program starts.
In this case we initialize or variable by calling the Factory function
RegisterShape with the ID of our shape and a pointer to the function that will be used to create new objects of that shape.
Isn't that neat?.
So if we have 50 shapes, we will have 50 variables to initialize, so the Factory RegisterShape function will get called 50 times.