Reputation: 1063
I have a singleton class for the settings of the software. In different places in the large software it is possible to getInstance and use it to access settings which are already read into the settings class from a file. However:
In initial call it is necessary to pass a "model name" (the software loads and runs simulation models) and based on the name, the software will load settings of the selected model.
Settings::getInstance("building1")
In later calls, it is not desired (or sometimes possible) to pass "model name" again. So it will be ideal if we can call without the model name.
What should I do in this scenario? Have 2 getInstance methods? Or set the "model name" to an static variable in Settings class before making the first call to getInstance? Or what?
Upvotes: 0
Views: 988
Reputation: 10357
Having 2 getInstance()
methods sounds like a recipe for disaster :) I would imagine the users of the class would always be asking: "Well which one do I use?" What would happen if someone called the wrong version first?
Instead of using 2 getInstance()
methods, I think it would be better to use the static variable approach, and set it early in the initialization phase. But this is also error-prone.
Even better would be to consider some sort of a factory that takes the model name upon instantiation and has a singleton internally. The factory could be something like this:
class SettingsFactory
{
public:
SettingsFactory(const std::string &modelName);
Settings *getUniqueSettingsInstance();
private:
SettingsFactory(); // cant instantiate the default ctor
// put the singleton stuff here
};
Upvotes: 2
Reputation: 31597
I'm not one to say singletons are evil, but here you really shouldn't be using them. A general rule of thumb: if your class has some state that is in any way perceivable from the outside, it should not be a singleton. Global state should be avoided for widely known reasons.
Your class clearly has state because it requires some initialization. Do not make it a singleton. Find some other way to structure your code.
Upvotes: 3
Reputation: 32418
If I understand you correctly, why don't you just overload the getInstance() method with a default value of NULL
? When you call your getInstance a second time, it shouldn't matter if the model name is a NULL char*
because you don't need it to construct your object this time.
class Settings
{
// ..
static Settings * getInstance(char * modelName = NULL);
}
Upvotes: 0