05. Create ———— Singleton mode

Source: Internet
Author: User

The singleton pattern is divided into two kinds, the lazy type and the A hungry man type. The difference is the time to create the instance. A hungry man creates an instance when the class is loaded, and the lazy type is created when it needs to be acquired.

Package Create.f.singleton;public class Singleton {private Singleton () {}protected static Singleton getinstance () { System.out.println ("Get Singleton Singleton object"); return instance;} private static Singleton instance = new Singleton (); A hungry man type  Note at this time thread safety}


Package create.f.singleton;//lazy public class Singleton2 {private static Singleton2 instance = Null;private Singleton2 () { }protected Static synchronized Singleton2 getinstance () {if (instance = = null) {SYSTEM.OUT.PRINTLN ("Initialize Singleton2 singleton") ; instance = new Singleton2 ();} return instance;}}


Package Create.f.singleton;public class Client {public static void main (string[] args) {Singleton Singleton = singleton.ge Tinstance (); Singleton s = singleton.getinstance (); System.out.println ("Whether the same object:" + (singleton = = s)); Singleton2 s2 = singleton2.getinstance (); Singleton2 s3 = Singleton2.getinstance (); Singleton2 S4 = Singleton2.getinstance (); System.out.println ("is the same object:" + (S2 = = S3 && S3 = = S4));}}


05. Create ———— 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.