I have a requirement to have a only a single instance of a class at any given point of time. Singleton is the obvious candidate. But I have some other conditions that are not typical of a Singleton.
So my implementation has the following static functions -
// To be called exactly once, everytime I enter the state
void MySingleton::CreateInstance(size_t count);
// To be called any no. of times during the state
MySingleton * MySingleton::GetInstance();
// To be called exactly once, when leaving the state.
void MySingleton::DestroyInstance();
Now this implementation is a major detour from conventional singleton implementation.
Is there any problem with such implementation?
Are there any better alternatives?
If you create an instance every time you enter a given state and destroy it every time you leave that state, it would make more sense to have the instance be owned by whatever is managing state transitions (or some other entity that is aware of the state transitions).
For example, you could have a smart pointer to an instance as a member variable of the state manager. When you transition into the state you can initialize it to a new instance and when you transition out of the state you can destroy that instance.
In my opinion, this would be cleaner than and preferable to using the singleton design (anti-)pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With