Example of the application of Java single example schema _java

Source: Internet
Author: User

The singleton pattern is used to ensure that a class has and has only one instance during the running of a program. The advantage is to resolve system resources as much as possible. You can implement a single case pattern by modifying the access rights of the construction method.

The code is as follows:

Copy Code code as follows:

public class Emperor {
private static Emperor Emperor = null;//declares a reference to a Emperor class

Private Emperor () {//The construction method is proprietary
}

public static Emperor GetInstance () {//instantiated reference
if (emperor = = null) {
emperor = new Emperor ();
}
return emperor;
}

public void GetName () {//Use normal method to output the name of the emperor
System.out.println ("I Am the Emperor: Tomorrow Science and Technology");
}

}

public class Test {
public static void Main (string[] args) {
System.out.println ("Creation Emperor 1 Objects:");
Emperor Emperor1 = Emperor.getinstance ();//Create Emperor Object
Emperor1.getname ()//output Emperor's name
System.out.println ("Creation Emperor 2 objects:");
Emperor Emperor2 = Emperor.getinstance ();//Create Emperor Object
Emperor2.getname ()//output Emperor's name
System.out.println ("Creation Emperor 3 objects:");
Emperor Emperor3 = Emperor.getinstance ();//Create Emperor Object
Emperor3.getname ()//output Emperor's name
}

}


Effect as shown:

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.