"Design pattern" Java Design Pattern the second lesson of the singleton mode

Source: Internet
Author: User

The singleton pattern is a specific design pattern that I have heard since I knew the noun of the design pattern. Its usage scenario is that there are some key resources that allow only one instance to be generated. If more than one instance is generated, there will be a lot of disruption to our reality.


Here are a few points I've summed up in the course of reading:

    • Ensure that a class has only one instance and provides a global access instance.
    • Implementing a singleton pattern in Java requires a private construction method, a static method, and a static instance.
    • Identify limitations on performance and resources, and then carefully select the appropriate scenario to implement the singleton to solve the multithreading problem (we must assume that all programs are multithreaded)
    • If more than one class loader is used, it may result in a single failure, resulting in multiple instances
    • There are two types of singleton patterns: Lazy mode and a hungry man mode
    • Lazy Mode: Loads the class faster, but the runtime gets the object at a slower speed because there is no object created for the class when the Singleton class is created. Thread is unsafe. To add the Syncronized keyword to the getinstance () method, if you need to add a double lock for efficiency
    • A hungry man mode: Loading classes is slow, but it is faster to get objects at run time. Because the object of the class was created when the Singleton class was created. is thread-safe.

The code of the singleton pattern itself is very small, but the amount of code does not mean it is very simple, to understand its true thinking, but also to use more thinking.

"Design pattern" Java Design Pattern the second lesson of the 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.