المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : c++ Factory pattern for large number of different classes. (answered)



C++ Programming
08-29-2009, 05:13 PM
(don't know if this should be in the design forum, anyway, I'm coding in C++)

I have a factory that will eventually create many, many different objects.

usually, I have something like (pseudo-c++-ish):

#include "type1Class.h"
#include "type2Class.h"
#include "type3Class.h"
#include "type4Class.h"

// typeXClass derive from BaseClass.
static BaseClass* MyClass::Builder(ObjectType type)
{
switch (type)
{
case type1: return new Type1Class;
case type2: return new Type2Class;
case type3: return new Type3Class;
case type4: return new Type4Class;
//...
}
}

Now, for a small number of classes this is manageable; but for a large number of classes it creates a large number
of includes and a huge switch.

Is there another pattern or methodology to clean that potential mess ?

I known I can put all typeXClass.h includes in a separate include file and have that one included; that will reduce the number of lines; any other tips hints ?

Thanks.

--------- edit------
Thanks to Stuart and Cédric; I will have a look at their solution first thing after coffee next monday!

This signature was proudly tested on animals.