Date Archives May 2020

Singleton Class

What is Singleton?

Restricts a class to instantiate its multiple objects and allows only one instance that has a control throughout the execution

Required properties: (1) should have only one instance and (2) should be globally accessible

 

Initialization

  • Early Initialization – initialize when the class gets loaded
    • Advantage: Simplicity
    • Disadvantage: it’s always initialized whether it is being used or not.
 
class SingletonClass {
    private static SingletonClass object = new SingletonClass();
    private SingletonClass() {}

    public static SingletonClass getInstance() {
        return object;
    }
}

 

  • Lazy Initialization – initialize only when it is required (general way to create a singleton class)
 
class SingletonClass {
    private static SingletonClass object;
    private SingletonClass() {}

    public static SingletonClass getInstance() {
        if(object == null) {
            object = new SingletonClass();
        } 
        return object;
    }
}

 

Examples of Singleton class

  1. Java.lang.Runtime – every app has a singleton instance of class Runtime to interface
  2. Logger – suitable for single log file generation that can prevent concurrent access
  3. Cache – client apps are able to use in-memory object with global point of reference.

 

References

  • https://www.geeksforgeeks.org/singleton-design-pattern-introduction/
  • https://stackoverflow.com/questions/19068468/what-is-meant-by-early-initialization-of-a-singleton-class-in-java