self-registering factory in C++

Started by
11 comments, last by Washu 12 years, 7 months ago
[font="arial, verdana, tahoma, sans-serif"]

Though there is a good reason to dislike that "central registration function". It makes things unneat. Instead of adding a single cpp file, you now have to add a header file, include that header file in some central file and modify existing code. Pretty much all the things you don't want.


Although I do think the central registration function is aesthetically displeasing, I haven't found it to be a maintenance problem in practice. It's something that both compilers and people understand easily, and adding another derived class doesn't require all that much extra work.[/font]
[font="arial, verdana, tahoma, sans-serif"] [/font]
[font="arial, verdana, tahoma, sans-serif"]Does anybody have a very different experience?[/font]
Advertisement
[font="arial, verdana, tahoma, sans-serif"]
Although I do think the central registration function is aesthetically displeasing, I haven't found it to be a maintenance problem in practice. It's something that both compilers and people understand easily, and adding another derived class doesn't require all that much extra work.[/font]
[font="arial, verdana, tahoma, sans-serif"] [/font]
[font="arial, verdana, tahoma, sans-serif"]Does anybody have a very different experience?[/font]

Well, I mean, I think we've all had the experience of forgetting to insert the register call for a class we're adding, which will result in a runtime error rather than a compile time error; howver, it's usually a very obvious error when it occurs. I just never liked having to include all the .h files for the derived classes in the cpp file where the central registration function happens, but maybe that's just the nature of factories.

...



Might as well make that simpler... and less error prone:
[source lang=cpp]//FactoryRegistration.cpp
#define REGISTER_FACTORY(x) void Register_##x(FactoryList*); Register_##x(list);
#define DECLARE_FACTORY(x) void Register_##x(FactoryList* list) { list->Add( new ##x() ); }
void RegisterFactories( FactoryList* list )
{
REGISTER_FACTORY( MyFactory );
REGISTER_FACTORY( Foo );
REGISTER_FACTORY( Bar );
}

//MyFactory.cpp
class MyFactory
{
};

DECLARE_FACTORY(MyFactory)

//main.cpp
int main()
{
FactoryList factories;
RegisterFactories( &factories );
}[/source]

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

This topic is closed to new replies.

Advertisement