Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton - Protected vs Private Constructor

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?

like image 553
Ron_s Avatar asked Aug 31 '11 11:08

Ron_s


1 Answers

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.

like image 97
Seb Holzapfel Avatar answered Jan 04 '23 09:01

Seb Holzapfel