Java Singleton mode

Source: Internet
Author: User

A single case pattern can be obtained by means of privatization and flexible application of static. After you have privatized the constructor, you can no longer create objects with new. A static method can only be called from a class name to get a singleton object (one of the objects).

Class Singleton{private static Singleton instance = new Singleton ();p rivate Singleton () {}public void print () {System.out. println ("Hello, singleton!");} public static Singleton getinstance () {return instance;}} public class SingleDemo01 {public static void main (string[] args) {//TODO auto-generated method Stubsingleton S1 = Single Ton.getinstance (); Singleton s2 = singleton.getinstance (); Singleton s3 = Singleton.getinstance (); S1.print (); S2.print (); S3.print ();}}

  

At this point, no matter how many objects, there is actually only one instance

Java Singleton mode

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.