----

Singleton Design Pattern Example

Singleton Design Pattern: This is the most simplest and most popular design pattern. This is a type of creational design pattern. This help us in creating a single object of a class. Multiple objects can not be created as we do for any normal class shown here.


If we have a class A then we can say
A a1 = new A();// creates a new object of A
A a2 = new A();// creates a new object of A
A a3 = new A();// creates a new object of A

Each time a new object of class A will be created so a1, a2 and a3 will refer three different instances of class A. But the same is not possible with a singleton class.
A a = new A() //not possible if A is a singleton class.

If you have a class 'Singleton.java' then, You can not create an object of this class using new operator. 
since the constructor of this class Singleton() will not be visible.
Singleton singleton = new Singleton();// is not possible, gives compile time error:

You can only get the object reference only by this way

Singleton singleton1 = Singleton.getInstance();// will return an instance of class Singleton 
Singleton singleton2 = Singleton.getInstance();// will return same instance of class Singleton 
or A a = A.getInstance();  // will return instance of class A 
Here singleton1 , singleton2 and singleton3 will refer the same instance of Singleton class.

When to use Singleton: We can use singleton in following situations.
  • If a class uses lots of resource when it is instantiated
  • If a class object takes lots of memory, so we can avoid creating multiple instances.
  • If you want only one class should handle your all requests for a specific behaviour. 
How to write a Singleton class: There are multiple ways to implement a Singleton class such that there can not exist another instance of same class in same JVM.
  • 1st way to create a Singleton class , ok but not thread safe
You can write a Singleton.java like this


public final class Singleton {
        /* only one object reference */
private static Singleton singleton = new Singleton();

private Singleton() {
/* make the constructor private so that this class cannot 
            be instantiated via new operator by any other class    */
}
       
        /* provide a way to get this class object */
public static Singleton getInstance() {
return singleton;
}

public void printMessage(String message) {
System.out.println(message);
}
}
  • 2nd way to create a Singleton class, Ok but not a good way to create a Singleton class

public final class Singleton {
          /* only one object reference */
private static Singleton singleton;

private Singleton() {
/* make the constructor private so that this class cannot
            be instantiated via new operator by any other class    */
}
    
        /* provide a way to get this class object */
public static synchronized Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public void printMessage(String message) {
System.out.println(message);
}
}

  • 3rd way to create a Singleton class, this is the best way to create a Singleton class, it is thread safe also.

public final class Singleton {
       /* only one object reference */
private static Singleton singleton;

private Singleton() { }
     
     /* provide a way to get this class object */
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
                         if (singleton == null) {//double check
singleton = new Singleton();
                         }
}
}
return singleton;
}

public void printMessage(String message) {
System.out.println(message);
}
}

How to test: You can test your Singleton class as following.
write a SingletonTest.java like this


public class SingletonTest {
public static void main(String[] args) {
//You can not create an object of Singleton using new operator
//Compile Time Error: The constructor Singleton() is not visible
//Singleton singleton = new Singleton();

//You can get object of Singleton like this
Singleton singleton = Singleton.getInstance();

//show the message
singleton.printMessage("This is a Singleton pattern test");
}
}


Output:
This is a Singleton pattern test
  • 4th way to create a Singleton class, Even a more better way to create a Singleton class is using enum, in this thread safety is guaranteed by JVM in Java 5 and above versions.

   public enum Singleton {
INSTANCE;
            // your class member function
public void showMessage(String message) {
System.out.println(message);
}
   }


Enum is the best way to create a singleton class, only the problem is if your singleton class extends any other class or has a parent then it is not possible to create a singleton using enum. Since enum dose not allow extends any class but interfaces are supported. so you can implements interfaces in enum class, also note that enum class can not be cloned so no duplicate object can be created.

How to test: You can test your Singleton class as following.
write a SingletonEnumTest.java like this


public class SingletonEnumTest {
public static void main(String[] args) {

//You can not create an object of Singleton using new operator
//Compile Time Error: The constructor Singleton() is not visible
//Singleton singleton = new Singleton();

//You can get object of Singleton like this
Singleton singleton = Singleton.INSTANCE;

//show the message
singleton.showMessage("This is a Singleton pattern test");
     //or you can directly call
     Singleton.INSTANCE.showMessage("This is a Singleton pattern test");
}
}

Output:
This is a Singleton pattern test
This is a Singleton pattern test

1 comment :

  1. I found in some other web site that inheriting from singleton design pattern is prohibited
    http://designpattern-tutorials.com/SingletonDesignPattern.html

    ReplyDelete