java Signleton schema details and sample code

  • 2020-05-10 18:08:24
  • OfStack

The Singleton pattern is the create pattern.

This pattern involves only one class that is responsible for creating its own objects.

This class ensures that only one object is created.

This class provides a way to access its 1-only object.

For example, when designing a user interface, we can only have one window for the main application. We can use the Singleton schema to make sure there is one of the MainApplicationWindow objects. The & # 8203; Instance.

The following code creates a main window class.

The MainWindow class has its own private construct and has its own static instance.

The main window class provides a static method to get its static instance of the outside world.

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 to help you, thank you for your support of this site!


Related articles: