Singleton mode is the creation mode.
This pattern involves only one class that is responsible for creating its own object.
This class ensures that only one object is created.
This class provides a way to access its unique object.
For example, when designing a user interface, we can only have a window for the main application. We can use Singleton mode to make sure there is an instance of the MainApplicationWindow object.
The following code will create a main window class.
The MainWindow class has its own private construct and has its own static instances.
The main window class provides a static method to get the world outside its static instance.
Our demo class will use the main window class to get a main window object.
class MainWindow { //create an object of MainWindow private static MainWindow instance = new MainWindow(); //make the constructor private so that this class cannot be //instantiated by other class private MainWindow(){} //Get the only object available public static MainWindow getInstance(){ return instance; } public void showMessage(){ System.out.println("Hello World!"); }}public class Main { public static void main(String[] args) { //Get the only object available MainWindow object = MainWindow.getInstance(); //show the message object.showMessage(); }}Thank you for reading, I hope it can help you. Thank you for your support for this site!