Singleton Design Pattern

Singleton Design Pattern says that a class should have only a single instance and that single object can be used by all other classes.

It Saves memory because the object is not created for each request. An only single instance is reused.

It is mostly used in thread pools, caching, configuration settings, etc.

We have to follow the below steps to create the singleton

Static member: It gets memory only

Private constructor: It will prevent instantiating the Singleton class from outside the class.

Static factory method: This provides the global point of access.

There are two ways of achieving singleton design pattern

Early Instantiation: instance create early if required or not

public class EagerSingleton {
   
private EagerSingleton(){}
   
private static final EagerSingleton singleton = new EagerSingleton();
   
public static EagerSingleton getSingleton(){
       
return singleton;
    }
}

Lazy Instantiation: instance create on demand

public class LazySingleton {
    private LazySingleton(){
    }
    private static LazySingleton singleton;
    public static LazySingleton getSingleton(){
        if(singleton == null){
            return singleton = new LazySingleton();
        }
        else{
            return singleton;
        }
    }
}

 

We can validate as below whether it is created single instance or not

public class SingletonTest {
    public static void main(String[] args) {
        LazySingleton obj1 = LazySingleton.getSingleton();
        LazySingleton obj2 = LazySingleton.getSingleton();
        System.out.println(obj1.hashCode()+", "+obj2.hashCode());
    }
}

 

No comments:

Post a Comment