The 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 gets created.
This class provides a way to access its unique object.
For example, when designing a user interface, we can only have one main application window. We can use the singleton mode to ensure that there is an instance of the Mainapplicationwindow object.
The following code creates a main window class.
The MainWindow class has its own private constructs and has its own static instance.
The main window class provides a static method to obtain the world outside of 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 this class cannot is//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 obj ECT = Mainwindow.getinstance ();
Show the message
object.showmessage ();
}
Thank you for reading, I hope to help you, thank you for your support for this site!