Single Class Instances (Not Singletons)

Started by
2 comments, last by Estauns 19 years, 11 months ago
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?
"Where genius ends, madness begins."Estauns
Advertisement
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
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
- John
Monostate, perhaps?

This topic is closed to new replies.

Advertisement