Monday, July 21, 2014

Singleton Implementations

Singleton implementation:

// Singleton implementation - thread safe
class Singleton {


    // private static variable to hold the Object
    private static Singleton singleInstance = null;

  
    // fields
    private int i = 0;  

 
    // private constructor to prevent creating objects
    private Singleton() {    }
   
    // static method to create this object and to return
    public static Singleton getSingleInstance() {
      if (singleInstance == null) {
        synchronized (Singleton.class) {
          if (singleInstance == null) // 2-level checking
            singleInstance = new Singleton();      
        } // Synchronized(Singleton.class)
      }
      return singleInstance;
    }
   
    // Class methods
    public void Message() {
        i++;
        System.out.println("Singleton example: " + i);
    }
}

public class SingletonThreadsafe {
    public static void main(String[] args) {
        Singleton oneInstance = Singleton.getSingleInstance();
        oneInstance.Message(); // Singleton example: 1
       
        Singleton secondInstance = Singleton.getSingleInstance();
        secondInstance.Message(); // Singleton example: 2
    }
}


Singleton implementation using Enum:

enum MySingleton
{
    RAGHU;
    public void sayHello()
    {
        System.out.println("Hello Raghu!");
    }
   
    public void sayBye()
    {
        System.out.println("Bye Raghu!");
    }
}


public class SingletonUsingEnum {
    public static void main(String[] args)
    {
        MySingleton ms = MySingleton.RAGHU;
        ms.sayHello();
        ms.sayBye();
        MySingleton ms1 = MySingleton.RAGHU;
       
        if(ms == ms1)
            System.out.println("Referring to same singleton class");
    }
}

No comments:

Post a Comment