3 ways to implement Java Singleton

Source: Internet
Author: User
Tags serialization

1. Instantiate by static member field

 Public classElvis {/*** Invoke private constructor instantiation object by final static member field*/     Public Static FinalElvis INSTANCE =NewElvis (); /*** Private constructors to prevent instantiation outside of the class*/    PrivateElvis () {} Public voidleavethebuilding () {System.out.println ("Leave The building ..."); }     Public Static voidMain (string[] args) {Elvis.INSTANCE.leaveTheBuilding (); }}

2, through the public static factory method

 Public classElvis {/*** Set the static member field to private*/    Private Static FinalElvis INSTANCE =NewElvis (); /*** Private constructors to prevent instantiation outside of the class*/    PrivateElvis () {}/*** Export a single instance through the public static factory method *@returnSingleton Instances*/     PublicElvis getinstance () {returnINSTANCE; }     Public voidleavethebuilding () {System.out.println ("Leave The building ..."); }     Public Static voidMain (string[] args) {Elvis.INSTANCE.leaveTheBuilding (); }}

3, through enumeration to return, this way is more concise, free to provide a serialization mechanism, absolutely prevent multiple instantiation, even in the face of multiple serialization and fan serialization attacks. Although this approach has not been widely adopted, this approach has become the best way to implement Singleton.

 Public classElvis {/*** Set the static member field to private*/    Private Static FinalElvis INSTANCE =NewElvis (); /*** Private constructors to prevent instantiation outside of the class*/    PrivateElvis () {}/*** Implemented by an enumeration type that contains a single element, as recommended (from the Java 1.5 release)*/     Public enumElvis1 {INSTANCE;  Public voidleavethebuilding () {System.out.println ("Leave The building ..."); }    }     Public Static voidMain (string[] args) {Elvis1.INSTANCE.leaveTheBuilding (); }}

3 ways to implement Java Singleton

Related Article

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.