Friday

Java singleton design pattern example

//Singleton design pattern - example class
//Eager initialization
public class SingletonObject {
    
       //Our static variable holding an instance of an existing singleton class
       private static SingletonObject singletonObject;
     
       static {
         // Initialize "singletonObject" only once
         singletonObject = new SingletonObject();
       }

    
       //The class constructor method is also private. We can not create the class instance outside of this class
       private SingletonObject() {
              //...constructor codes
       }
    
       //The method that returns the single instance of the SingletonObject class
       public static SingletonObject getInstance() {
              return singletonObject;
       }

       //Prevent cloning of class by throwing CloneNotSupportedException
       @Override
       public Object clone() throws CloneNotSupportedException {
              throw new CloneNotSupportedException();
       }
}

//Singleton design pattern - example class
//Lazy initialization
public class SingletonObject {
    
       //Our static variable holding an instance of an existing singleton class
       private static SingletonObject singletonObject = null;
     
       //The class constructor method is also private. We can not create the class instance outside of this class
       private SingletonObject() {
              //...constructor codes
       }
    
       //The method that returns the single instance of the SingletonObject class
       public static SingletonObject getInstance() {
          if(singletonObject == null) {
                 synchronized (SingletonObject.class) {
                        //double-checked locking
                        if(singletonObject == null) {
                              singletonObject = new SingletonObject();
                        }
                 }
                 
          }
              return singletonObject;
       }

       //Prevent cloning of class by throwing CloneNotSupportedException
       @Override
       public Object clone() throws CloneNotSupportedException {
              throw new CloneNotSupportedException();
       }
}



No comments:

Post a Comment