Singleton Design Pattern

If you need to instantiate just only one object of a particular class, use the Singleton pattern. Think of it as a “stage” and “performers”. There is only one stage and many performers that could use this stage. Think of the stage as one and only one object that you can instantiate. Singleton.

This is an example of a Singleton object oriented Design pattern:

  • Singleton has no public constructor. Create an empty private constructor.
  • Create a private static class variable and call it INSTANCE. This class variable can be shared among all objects of this class, but we are creating only one. Assign null to the INSTANCE class variable.
  • Create a public static method called getInstance() that method should return an INSTANCE class variable of the Stage type.
  • Check if the INSTANCE has a “null” value. If yes, create an object of the type Stage and assign it to the INSTANCE variable.
public class Stage {

    private static Stage INSTANCE = null;	
    
    private Stage() {}
	
    public synchronized static Stage getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Stage();
        }
        return INSTANCE;
    }
}

Now, each time you need an object of the Stage class just use the getInstance() method. If an object of this type is already exists, it will be returned. If not, a new object will be created.

public static void main(String[] args) {
    Stage stage = Stage.getInstance();
}

To prevent creating two or more singleton objects in multi-threading environment we have to put the synchronized keyword in the getInstance() method.