Java Signleton mode and sample code _java

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.