In most cases, instances of objects are created, which result in several objects being created from the same class. Using the Singleton pattern, we can ensure that only a single object of this class is created during the lifetime of the application.
Step 1: Create a Singleton Class
public class SingletonClass
{
//Create singleton object
private static SingletonClass singletonInstance = new SingletonClass();
//Create private constructor so this class cannot be instantiated
private SingletonClass() {}
//Get an instance of this class
public static SingletonClass getInstance()
{
return singletonInstance;
}
public void message() { System.out.println("Singleton Instance");
}
}
Singleton Demo:
public class SingletonDemo {
public static void main (String[] args) {
//The constructor SingleObject() is not available
//SingletonClass mySingleton= new SingletonClass();
//Correct Way
SingletonClass mySingleton= SingletonClass.getInstance();
//show the message
mySingleton.showMessage(
}
}
Leave a comment