Saturday, 6 February 2016

Singleton Design Pattern in Java

Definition: A singleton class is a class that is instantiated only once. This is typically accomplished by creating a static field in the class representing the class. A static method exists on the class to obtain the instance of the class and is typically named something such as getInstance(). The creation of the object referenced by the static field can be done either when the class is initialized or the first time that getInstance() is called. The singleton class typically has a private constructor to prevent the singleton class from being instantiated via a constructor. Rather, the instance of the singleton is obtained via the static getInstance() method.

Code Description:
The SingletonSolution class is an example of a typical singleton class. It contains a private static SingletonSolution field. It has a private constructor so that the class can't be instantiated by outside classes. It has a public static getInstance() method that returns the one and only SingletonSolution instance. If this instance doesn't already exist, the getInstance() method creates it. The SingletonSolution class has a public sayHello() method that can be used to test the singleton.


SingletonSolution.java

package com.krishna;

public class SingletonSolution {

 private static SingletonSolution singletonSolution = null;

 private SingletonSolution () {
 }

 public static SingletonSolution getInstance() {
  if (singletonSolution == null) {
   singletonSolution = new SingletonSolution ();
  }
  return singletonSolution ;
 }

 public void sayHello() {
  System.out.println("Hello!! Krishna Kumar Chourasiya !!!");
 }
}

 ======================================================================

The SingltonSolutionMain class obtains a SingletonSolution singleton class via the call to the static SingletonSolution.getInstance(). We call the sayHello() method on the singleton class. Executing the SingltonSolutionMain class outputs "Hello !! Krishna Kumar Chourasiya !!!" to standard output. 

SingltonSolutionMain.java

package com.krishna;

public class Demo {

 public static void main(String[] args) {
  SingletonSolution singletonSolution = SingletonSolution.getInstance();

  singletonSolution.sayHello();
 }

}



2 comments:

  1. If i serialize the singleton object and deserialize it twice, i will end-up with two object per JVM, whole purpose of singleton is beaten now.

    ReplyDelete
    Replies
    1. You need to implement the appropriate readObject() and writeObject() to ensure that serialization does not make a separate copy.

      Delete

Monads in Scala

Monads belongs to Advance Scala   concepts. It  is not a class or a trait; it is a concept. It is an object which covers other object. A Mon...