Java design Pattern--Singleton mode

Source: Internet
Author: User

A hungry man single-case mode:
 Package Com.design.singleton;  Public class Eagersingleton {    privatestaticfinalnew  Eagersingleton ();     Private  Eagersingleton () {}    publicstatic  Eagersingleton getinstance () {        return  Eager_singleton;    }}

When this class is loaded, the static variable Eager_singleton is initialized.

Lazy Single-Case:
 PackageCom.design.singleton; Public classLazysingleton {Private StaticLazysingleton Lazysingleton =NULL; PrivateLazysingleton () {} Public synchronized StaticLazysingleton getinstance () {if(Lazysingleton = =NULL){            return NewLazysingleton (); }        returnLazysingleton; }}

the "difference" a hungry man singleton mode instantiates itself when it is loaded. From the perspective of resource utilization, a hungry man is almost the same as the lazy. In terms of speed and reaction time, a hungry man is more than a lazy block. Lazy in the instantiation of the time, need to deal with multi-threaded problems.

There's a lot more to use.

Static internal class Single example:

 PackageCom.design.singleton; Public classInnersingleton {PrivateInnersingleton () {}Private Static classinner{Private StaticInnersingleton Instance =NewInnersingleton (); }     Public StaticInnersingleton getinstance () {returninner.instance; }         Public voiddosomething () {//Do something    }    }

This single thread-safe

Java design Pattern--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.