Singleton Pattern

Singleton pattern is a creational design pattern. It ensures a class has only one instance created, and provides a global point of access to it. The implementation includes just-in-time initialization and initialization on first use.

Singleton Pattern

Singleton class is one of the simplest design patterns, but it poses many challenges. One of the key challenge is how to keep Singleton class as Singleton?

Singleton related interview questions

  • What is Singleton class? When to use it?
  • Write code for getInstance() method of a Singleton class in Java
  • What is lazy and eager loading of Singleton? How to implement them.
  • What is double checked locking in Singleton?
  • Why Singleton is Anti pattern?
  • Can you replace Singleton with Static Class in Java?
  • Difference between Singleton and Static Class in java? Any pro / cons?

Implementation 1

The singleton instance is initialized during class loading. Since Singleton instance is static and final variable, it is initialized when class is loaded into memory. In this solution, the creation of instance is thread-safe.

Usage will be

Implementation 2
A singleton instance is created by synchronize getInstance() method, and is thread-safe. However, it is unnecessarily expensive due to cost of synchronization at each call.

Implementation 3
It is an implementation of double checked locking of Singleton which will minimize the cost of synchronization by locking critical section of code (see example code).

It is noted that we need make INSTANCE a volatile variable. Otherwise, it is still broken as another thread can see a half initialized instance of Singleton.

Implementation 4
It is an idea approach to utilize enum which can have its own methods and properties.

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

One thought on “Singleton Pattern

  1. Pingback: Software Design Patterns

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">