Rakesh  avatar

Singleton Design Pattern

rakeshbecse

Published: 01 Apr 2018 › Updated: 01 Apr 2018Singleton Design Pattern

Singleton Design Pattern

Singleton pattern:

  • Singleton pattern belongs to the creational pattern.
  • It allows one instantiation or object for JVM

Rules for singleton pattern:

  • The constructor should be private.
​​private Singleton()
{

}​
  • We can not create an object outside of the class.
Singleton singleton=new Singleton(); //Not possible to create an object using new keyword because the constructor is private

Advantages of singleton pattern:

  • It controls multiple object creations by allowing only one-time creation.

Use cases of singleton pattern:

  •  Logging is a popular use of Singletons.  It provides one single access point to an applications log file.

Issues with singleton pattern:

  • If two threads call the getInstance() method at the same time, you can end up with two singletons. 
  • If we make getInstance() method synchronized then it solves the issue, but we need to sacrifice performance because synchronized getInstance()  is a costly operation.

Leave Singleton Design Pattern to:

Written by

I (Rakesh P ) am working in a product based software company in Chennai. I have been working in NLP (Natural Language Processing). When I was doing Engineering

Read more #softwaredesignpattern posts


Best Posts From Rakesh

We have not curated any of rakeshbecse's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Rakesh