A single-instance design pattern for Java Design Patterns (Singleton)

Source: Internet
Author: User

Single Case design mode

The singleton pattern in the daily development uses is also more, as the name implies is a class of objects in the entire system can only have a

Advantages:

1. Singleton mode prevents other objects from instantiating their own copy of a singleton object, ensuring that all objects have access to a unique instance

2, because there is an instance object in the whole system, avoid the frequent creation and destruction of objects, so can save system resources

3. Avoid multiple occupancy of shared resources

4. Create this singleton object yourself, and avoid creating it when you use it.

Disadvantages:

1, the singleton mode does not have the abstraction layer, so the extensibility is poor

2, not applicable to changing objects, if the same type of objects need to be used in different scenarios, the singleton will cause data errors

3, misuse of the singleton mode will bring some negative problems, such as to save system resources to the database connection pool object design as a singleton mode, may result in the sharing connection pool object too many programs and a connection pool overflow, if the instantiated object is not exploited for a long time,

The system is considered garbage and is recycled by GC resulting in loss of object state

  Lazy mode:

      

A Hungry man mode:

Dual Lock mode:

      

Summarize:

  1, lazy mode features: Thread insecure, load classes faster, run time to get objects slower,

2, a Hungry man mode features: Thread safety, load class is slow, run time to get objects faster

3, double lock mode: Thread-safe, load class faster, run-time to get objects at a slower speed

Code address

    

    

A single-instance design pattern for Java Design Patterns (Singleton)

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.