Design mode: 5) Singleton mode

Source: Internet
Author: User

1. Concept
Ensure that a class has only one instance (construction method privatization) and provides a global access point (static GetInstance method) to access it.
2. Realization of Ideas
To control that a class is created only by an instance, the first problem is to take the permissions of the created instance back and let the class itself take care of the creation of its own class instance, and then this class provides a way for the external access to the class instance.
3. How to implement
1) Lazy Type
2) A Hungry man type
Lazy: Always create an object instance when the Dodge is not open.
A hungry man: Since you are hungry, you are more anxious when creating an object instance, so you create an object instance when the class is loaded.
4. Example (lazy type)
public class singleton{

   //私有话的构造函数   private Singleton(){   }    //静态的存储变量    private static Singleton mInstace;    //获得实例的入口    public static Singleton getInstance(){        if(mInstance == null){            mInstance = new Singleton();        }        return mInstance;    }

}

Design mode: 5) 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.