Quantcast
Channel: Alternatives to the singleton pattern - Software Engineering Stack Exchange
Viewing all articles
Browse latest Browse all 11

Answer by Randall Cook for Alternatives to the singleton pattern

$
0
0

If your needs from the singleton can be boiled down to a single function, why not just use a simple factory function? Global functions (probably a static method of class F in your example) are inherently singletons, with uniqueness enforced by the compiler and linker.

class Factory{public:    static Object* createObject(...);};Object* obj = Factory::createObject(...);

Admittedly, this breaks down when the operation of the singleton cannot be reduced to a single function call, though perhaps a small set of related functions might get you by.

All that being said, items 1 and 2 in your question make it clear that you really just want one of something. Depending on your definition of the singleton pattern, you are either already using it or very close. I don't think you can have one of something without it being a singleton or at least very close to one. It's just too close to the meaning of singleton.

As you suggest, at some point you have to have one of something, so perhaps the problem is not having a single instance of something, but of taking steps to prevent (or at least discourage or minimize) abuse of it. Moving as much state out of the "singleton" and into parameters as possible is a good start. Narrowing the interface to the singleton also helps, as there are fewer opportunities for abuse that way. Sometimes you just have to suck it up and make the singleton very robust, like the heap or the filesystem.


Viewing all articles
Browse latest Browse all 11

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>