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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With