5 ways to write a singleton and why you shouldn’t !

One Singleton to Rule ‘em All !

Sineth Neranjana
6 min readSep 14, 2017

The singleton design pattern is one of the most inappropriately used patterns. Singletons are intended to be used when a class must have exactly one instance, no more, no less. Designers/ coders/ developers frequently use singletons in a misguided attempt to replace global variables. A singleton is, for all intents and purposes, a global variable.

In this article we will go from the most dumb down version of a singleton to an ironclad guaranteed implementation of a singleton that will not bow down to multiple instantiation, even in the face of sophisticated serialization or reflection attacks.

While implementing Singleton we have 2 options,
1. Early loading
2. Lazy loading

Lazy loading adds a bit overhead(lots of, to be honest) so use it only when you have a very large object or a heavy construction code AND also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization. Otherwise choosing early loading is a good choice.

Early Loading Singleton

--

--

Sineth Neranjana
Sineth Neranjana

Written by Sineth Neranjana

An every day developer writing stuff to share knowledge

Responses (4)