(I hope that it's okay to ask a question on design patterns here. It's not C++ specific but, well, I plan to implement the pattern in C++, and no other board seemed more appropriate.)
At the moment, the code I'm working on has a whole bunch of "Factories". By a "Factory", I simply mean a class that contains a whole bunch of methods that return instances of objects. These classes have been implemented as Singletons. For example:
So, to get a Widget, client code calls WidgetFactory::getInstance().getWidget();Code:class WidgetFactory
{
static WidgetFactory& getInstance();
Widget getWidget();
};
Now, I'm trying to understand how the Abstract Factory pattern can help here so that the creation of Widgets aren't decided at compile time. For example, there might be two types of Widgets: SmallWidgets and BigWidgets (yeah, my examples suck, but it's all that's coming to me at the moment :) ).
If I understand the Abstract Factory pattern correctly, then this is implemented like this:
Okay, finally to the actual question. :) What I don't get is how I actually am supposed to instanciate the factory itself. Before, it was simply a singleton, so that wasn't a problem. Now, I need to select whether I want big or small widgets (say, from a configuration file), and then use the appropriate factory. But say I have 10 different classes that all need to create widgets... do they all need to check the config file themselves? Or maybe there should be another class, implemented as a singleton, that is responsible for checking the config file, and returning the factory? (A factory factory?) Rough pseudocode:Code:class WidgetFactory
{
virtual Widget* getWidget() = 0;
};
class SmallWidgetFactory
{
virtual Widget* getWidget() { return new SmallWidget(); }
};
class BigWidgetFactory
{
virtual Widget* getWidget() { return new BigWidget(); }
};
On preview, this question barely seems to make sense, even to me. :) I guess I'm just drowning in details at the moment. I guess my question is this: does this seem like a reasonable design? Is there a better way to do this? Can I avoid Singletons altogether maybe (I keep getting told I should :) )?Code:class ConfigFileReader
{
static ConfigFileReader& getInstance();
WidgetFactory* getWidgetFactory()
{
if (config file says small widgets)
{
return SmallWidgetFactory;
}
else
{
return BigWidgetFactory;
}
}
};