Java single-Instance design pattern

Source: Internet
Author: User

Learn Java single-case design model, read a few better articles and some of the book information, here to do a summary for Exchange learning

The role of a single-case design model

The singleton design pattern guarantees that there is only one object for a class and everyone is using the same object (which is verified in code below).

Second, the characteristics of the single case design pattern

1, the Singleton class has and can only have one instance

2. A singleton class must create an instance of itself

3. The Singleton class must provide a way for other class objects to get the instance

Iii. steps to create a singleton class

1. Privatization of the constructor of this class

2. Create a class object in this class through new

3. Define a common method that returns the created object and the method used by other objects to get the instance

Four, two common ways and Java code

1  Public classSingledemo {2 3      Public Static voidMain (string[] args) {4         //TODO auto-generated Method Stub5 6Single2 S1 =single2.getinstance ();7Single2 s2 =single2.getinstance ();8System.out.println (S1 = =S2);9         //output True, stating that the object is the same, validating a singleton design patternTen     } One  A } - //a hungry man type - classSingle1 the { -     PrivateSingle1 () {} -     Private StaticSingle1 s =NewSingle1 (); -      Public StaticSingle1 getinstance () +     { -         returns; +     } A } at //Lazy Type - classSingle2 - { -     PrivateSingle2 () {} -     Private StaticSingle2 s =NULL; -      Public StaticSingle2 getinstance () in     { -         if(s = =NULL) tos =NewSingle2 (); +         returns; -     } the}

Java single-Instance design pattern

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.