Singleton Pattern

2 minute read

Hey. You can’t initialize me, but you can get the only one instance of myself which is shared across your app by asking my static sub-routine. I can help you with what I can. Singleton class

This is a continuation of the software design pattern series. You can checkout the previous posts from my-blog

Singleton pattern

Ever been in a situation where you just need to restrict initiation of a class and also wanted to ensure that only one instance of the class should be present in the JVM at a given time? Then Singleton pattern is your way to go.


I’d be honest here. Singleton pattern is dangerous. Use it only if it is really needed. It even breaks the Single responsibility principle from SOLID* as here, the same class has two responsibilities including initiation of itself and having it’s own behavior as well.

Ok. So where can I use Singleton pattern?

One of the good places where I’d say Singleton pattern is a good candidate is in Logging. When logging to a file from your app, it’s better to go through a single point of contact which eliminates a lot of complexities.

Example 1: Logging to a file from your app.

Example 2: Reading a configuration file and keeping them in memory in the class for faster access across the app.

Cool. So how to implement Singleton pattern?

In Singleton pattern, just one component gets involved excluding the Client.

  • SingletonClass

-> SingletonClass

The class has the constructor as private, so it cannot be initialized outside the class.
The class has its own reference with private modifier.
There are two ways to initialize this reference.

  • Initialize during the class loading (ie) when declaring the instance, just add the initializing part too. Check example code 1
  • Initialize during the first time getInstance() method is called from this class. Check example code 2

Thread safety needs to be considered while using the singleton pattern as in multi threaded environment, the same object is going to be shared across threads. So handling them properly should be a high priority.

Design Structure

image tooltip here

photo courtesy: link

Sample code



As seen in the code example, the instance could be get across the application using the getInstance() method and it will guarantee to have just single instance of that class to be alive at a given time.

PS: Why Singleton is dangerous. Have a look link
* -> More on the SOLID principles in the future.

Thank you. Hope this helps. Looking forward to more learning and sharing. Cheers :)
Connect, share and text me about your views. We can have some discussion :)

Stay connected:

Subscribe: Subscribe to Build with Sammie feed for newsletter by Email

Connect on Twitter

Connect on Linkedin