Reputation: 1459
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 protected
? Wouldn't private
do the trick as well?
Upvotes: 13
Views: 6672
Reputation: 3873
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
.
Upvotes: 10
Reputation: 809
It's all about inheritance.
class lazy_singleton: public singleton {};
will be the same singleton with singleton constructor
Upvotes: 0
Reputation: 133024
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.
Upvotes: 4