Singleton design mode (hunger and lazy)

Source: Internet
Author: User

Singleton design mode (hunger and lazy)

1. When to use it: It is recommended that the configuration file be encapsulated into an object when multiple programs read a configuration file. It is convenient to operate on the data, and ensure that multiple programs read the same configuration file object. Therefore, the configuration file object must be unique in the memory.

2. essence: Ensure the uniqueness of an object in the memory of a class.

3. thoughts:

A. Do not allow other programs to create such objects.

B. Create an object in this class.

C. Provide external methods for other programs to obtain this object.

4. Solution steps:

 

A. the constructor Initialization is required to create objects. As long as the constructor in this class is privatized, other programs cannot create such objects;

B. Create an object of this class in the class;

C. Define a method and return this object so that other programs can obtain this class object through the method. (Role: Controllable)

 

5. Code implementation:

 

A, // hungry Chinese

Class Single {

Private Single (){}//Private constructor.

Private staticSingle s = new Single ();//Create a private and static class object.

Public static SinglegetInstance (){//Defines public and static methods and returns this object.

Return s;

}

}

 

 

B. Lazy: delayed loading.

 

Class Single2 {

Private Single2 (){}

Private staticSingle2 s = null;

Public static Single2getInstance (){

If (s = null)

S = new Single2 ();

Return s;

}

}


 

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.