Chapter 2: create and destroy objects. Item3: Use a private constructor or enumeration type to enhance the singleton attribute.

Source: Internet
Author: User

Three methods for declaring a singleton class:

Package com. twoslow. cha2;/*** you can call the private constructor through the accessibleobject. setaccessible () reflection mechanism. * @ Author sai **/public class singleton01 {private singleton01 () {} public static final singleton01 instance = new singleton01 (); Private object readresolve () {return instance ;}}
Package com. twoslow. cha2;/*** you can call the private constructor through the accessibleobject. setaccessible () reflection mechanism. * @ Author sai **/public class singleton02 {private singleton02 () {} Private Static final singleton02 instance = new singleton02 (); public static singleton02 getinstance () {return instance ;} private object readresolve () {return instance ;}}
 
Package com. twoslow. cha2;/*** it is not enough to add implements serializable to the Declaration to achieve single-instance class serialization. * All instance domains must be declared as transient and a readresolve method is provided. Otherwise, * a new instance is created every time a serialized instance is deserialized. * The Enumeration type of a single element provides a serialization mechanism, which is the best way to implement Singleton. * @ Author sai **/Public Enum singleton03 {instance ;}
 

 

 

Chapter 2: create and destroy objects. Item3: Use a private constructor or enumeration type to enhance the singleton attribute.

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.