Archived

This topic is now archived and is closed to further replies.

Estauns

Single Class Instances (Not Singletons)

Recommended Posts

Is there a design pattern that''ll create a single instance of a class (and only a single instance) but not globally accessible like a singleton? I''ve heard them called mono-instance classes but I can''t find anything on Google. I''m looking to protect some classes from being instantiated more than once. Having more than one Graphics class for example, could be horrible. Or two Sound systems. Is there a way?

Share this post


Link to post
Share on other sites
Nothing requires Singletons to be globally accessible. In particular, Singletons are often seen as private inner classes. Of course, in such cases it''s often just as easy and effective to have a single static instance, and simply remember not to make more of them.


"Sneftel is correct, if rather vulgar." --Flarelocke

Share this post


Link to post
Share on other sites
If you want to limit instances of your class to some number, like one, and you don''t want to use the typical singleton pattern you could just put a static int in the cpp file of the class and use it to track the number of instances of that class by incrementing it in the constructor and decrementing it in the destructor. Then, in the constructor you could just assert that NumMyClassInstances < MaxNumMyClassInstances.

Not the most elegant solution, but if it''s a closed system it should work to keep ya honest

-John

Share this post


Link to post
Share on other sites