Java Design pattern Single-instance mode

Source: Internet
Author: User

--------------------------------------------------

Directory

1. Definition

2. Common centralized single-instance implementations

A. A hungry man, thread-safe but low-efficiency

B. Implementation of the Singleton pattern: full-Chinese, non-thread-safe

C. Full-Han style, simple implementation of thread safety

D. Thread-safe and high efficiency single-case mode optimal scheme

3. Summary

A. Using the enumeration's singleton pattern

B. Using enumerations, static calls, initializing once

--------------------------------------------------

1. Definition

Make sure that a class has only one instance and provides a global access point!

2. Common centralized single-instance implementations

A. A hungry man, thread-safe but low-efficiency

/** * Single-instance mode implementation: A Hungry man, thread-safe but inefficient*/   Public classSingletontest {//to define a private construction method    Privatesingletontest () {}//set the instance object of itself to a property, plus the static and final modifiers    Private StaticFinal Singletontest instance =Newsingletontest (); //static methods return instances of this class     Public Staticsingletontest getinstancei () {returninstance; }    }

B. Implementation of the Singleton pattern: full-Chinese, non-thread-safe

/*** Single-mode implementation: full-Chinese, non-thread-safe **/   Public classSingletontest {//Define private construction methods (prevent instantiation with new Singletontest ())    Privatesingletontest () {}//define a variable of type singletontest (uninitialized, note that the final keyword is not used here)    Private StaticSingletontest instance; //defines a static method (Singletontest is initialized when called, but can cause repeated initialization problems when multithreaded access)     Public Staticsingletontest getinstance () {if(Instance = =NULL) Instance=Newsingletontest (); returninstance; }   } 

C. Full-Han style, simple implementation of thread safety

/*** Single-instance mode implementation: Full-Chinese, thread-safe simple implementation **/   Public classSingletontest {//Define private construction methods (prevent instantiation with new Singletontest ())    Privatesingletontest () {}//define a variable of type singletontest (uninitialized, note that the final keyword is not used here)    Private StaticSingletontest instance; //define a static method (re-initialize the singletontest when called and use synchronized to avoid multi-threaded access, which can cause heavy re-initialization problems)     Public Static synchronizedsingletontest getinstance () {if(Instance = =NULL) Instance=Newsingletontest (); returninstance; }   } 

D. Thread-safe and high efficiency single-case mode optimal scheme

/*** Single mode optimal scheme * thread safe and high efficiency **/   Public classSingletontest {//Define a private construction method    Privatesingletontest () {}//defines a static private variable (uninitialized, does not use the final keyword, and volatile guarantees the visibility of the instance variable when multi-threaded access is avoided, and is called by another thread when the other variable property is not assigned when instance initialized)    Private Static volatileSingletontest instance; //defines a common static method that returns an instance of the type     Public Staticsingletontest getistance () {//when an object is instantiated (without using a synchronous block of code, instance is not equal to NULL, the object is returned directly, improving operational efficiency)        if(Instance = =NULL) {            //Synchronizing code blocks (when an object is not initialized, use a synchronous block of code to guarantee that the object will not be created again after the first creation of the multi-threaded access)            synchronized(Singletontest.class) {                //Uninitialized , the initial instance variable                if(Instance = =NULL) {instance=Newsingletontest (); }               }           }           returninstance; }   }

3. Summary

  

"Above singleton mode" traditional two private one public (private construction method, private static instance (lazy instantiation/Direct instantiation), public static Fetch method) involves thread safety problem (even if there are multiple check locks can also be broken by reflection of the single case)

The most secure way to implement a singleton now is through an internal static Enum method, because the JVM guarantees that the enum cannot be reflected and that the constructor method executes only once. As follows

A. Using the singleton pattern of enumerations

/*** Use the enumeration's singleton mode * *@authorYzl *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/ Public classenumsingleton{PrivateEnumsingleton () {} Public StaticEnumsingleton getinstance () {returnSingleton.INSTANCE.getInstance (); }        Private Static enumsingleton{INSTANCE; PrivateEnumsingleton Singleton; //the JVM will ensure that this method is absolutely called only once        PrivateSingleton () {Singleton=NewEnumsingleton (); }         PublicEnumsingleton getinstance () {returnSingleton; }    }}

B. Using enumerations, static calls, initializing once

Importjava.util.ArrayList;Importjava.util.List;/*** Initialization of the elegant implementation * can be called in the static, * can also be called in the normal method, are guaranteed to initialize only once * * Of course, the code of the enum block directly into the private static method of the Staticinittest class is also possible * /c9>@authorYzl *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/ Public classStaticinittest {Private StaticList<integer> dataList =NULL; Static{dataList=Singleton.INSTANCE.init (); }        /*** * Single-case mode to populate data * *@authorYzl *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/    Private Static enumSingleton {INSTANCE; PrivateList<integer>list; PrivateSingleton () {filldata (); }        /*** * Initialize data * *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/        Private voidFilldata () {list=NewArraylist<integer> (5);  for(inti = 1; i<6; i++) {list.add (i); }        }        /*** * Initialize the portal * *@see[Related Classes/methods] (optional) *@since[Product/module version] (optional)*/         PublicList<integer>init () {returnlist; }    }}

Reference: Java single-instance enum implementation method

Java design Pattern--Singleton mode

Java Design pattern Single-instance 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.