Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Singleton design question

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.

  1. The lifetime of the singleton is not the lifetime of the program. This object has to be created every time I enter a particular state and destroyed when I leave the state. For the entire duration of the state, I cannot create another instance of the class.
  2. Every time, I enter the state and create a new instance, I need to pass a variable to the singleton. Its a number, based on user selection.

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?

like image 408
Happy Go Lucky Avatar asked Nov 29 '22 18:11

Happy Go Lucky


1 Answers

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.

like image 173
James McNellis Avatar answered Dec 04 '22 13:12

James McNellis