When designing singletons, why is the constructor made protected
and not private
? This is based on what I've seen over the web.
We want to control the number of instances made of that class, fair enough, but why protecte开发者_Python百科d
? Wouldn't private
do the trick as well?
Firstly, Singletons in the vast majority of cases are a bad idea (Why?). Use them even less than global variables.
It's so that subclasses can instantiantiate the Singleton base class, returning it as a part of itself in it's own GetInstance()
-type function. This is the reason that it is done in Design Patterns. Therefore it's only really relevent if you plan on inheriting from the Singleton.
GoF says, (page 130, Subclassing the Singleton class);
A more flexible approach uses a registry of singletons. Instead of having
Instance
define the set of possible singleton classes, the singleton classes can register their singleton instance by name in a well-known registry.
In using a registry of singletons, a protected
constructer in the base Singleton is still required (according to the implementation given)
In short; Make it protected
if you plan on inheriting from the Singleton. Otherwise, go with private
.
Using singletons is bad. Period.
That said, the constructor can be private, no problem. But what if you want to derive another singleton from your singleton(as if having one singleton wasn't bad enough)? In that case the derived class needs access to the base singleton constructor.
It's all about inheritance.
class lazy_singleton: public singleton {};
will be the same singleton with singleton constructor
精彩评论