A single-instance pattern of Java design patterns

Source: Internet
Author: User
Tags volatile

Singleton mode: As the creation mode of an object, a singleton pattern ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole.

Characteristics:

    1. A singleton class can have only one instance
    2. The Singleton class must create its own unique instance
    3. The Singleton class must provide this instance to all other objects

A hungry man-type singleton class:

Features: Typical space-changing time, whether you use it or not will create an instance

 PackageSingleton;/*** A hungry man type single example: Typical space-changing time, whether you use it or not will create an instance*/ Public classEagersingleton {Private StaticEagersingleton instance =NewEagersingleton (); /*** Building a private constructor*/    PrivateEagersingleton () {}/*** Static Factory method *@return     */     Public StaticEagersingleton getinstance () {returninstance; }}

Lazy single-Case class:

Characteristics: Typical time to change space, need to use the time to create objects;

 PackageSingleton;/*** Lazy Single example: Typical time to change space, need to use the time to create objects; * Although it is thread-safe, it reduces the speed of the entire visit and is judged every time. */ Public classLazysingleton {Private StaticLazysingleton instance =NULL; PrivateLazysingleton () {} Public Static synchronizedLazysingleton getinstance () {if(Instance = =NULL) {instance=NewLazysingleton (); }        returninstance; }}

Double check plus lock class:

Features: The realization of thread safety, but also can not be greatly affected by performance;

The first check: not every time into the GetInstance method need to synchronize, but first different steps, enter the method, first check whether the instance exists, if not exist before the following synchronization block;

Second check: After entering the synchronization block, again check the existence of the instance, if not exist, in the case of synchronization to create an instance;

 PackageSingleton;/*** Double check yoke: the implementation of thread safety, but also can not be greatly affected by the performance; * First check: Not every time into the GetInstance method need to synchronize, but first out of sync, enter the method, first check whether the instance exists, if not exist before the following synchronization block; Second check: After entering the synchronization block, again check the existence of the instance, if not exist, in the case of synchronization to create an instance;*/ Public classSingleton {//The value of a volatile variable is not cached by the local thread, and all read and write to the variable is directly operating shared memory, ensuring that multiple threads are able to handle the variable correctly. //Note: In Java1.4 and previous versions, many JVM issues with the implementation of the volatile keyword will result in a "double check lock" failure, so the "double check lock" mechanism can only be used in versions Java5 and above.     Private Static volatileSingleton instance =NULL; PrivateSingleton () {} Public StaticSingleton getinstance () {//Check that the instance exists before entering the following synchronization code block if it does not exist        if(Instance = =NULL) {            //synchronization blocks, thread-safe creation instances            synchronized(Singleton.class) {                //Check again if the instance exists, and if it does not exist, actually create the instance                if(Instance = =NULL) {instance=NewSingleton (); }            }        }        returninstance; }}

Lazy Loading Internal implementations:

Features: Delayed load and thread safety are implemented

 PackageSingleton; Public classSingleton {PrivateSingleton () {}/*** Class and the inner class, that is, the static member-type inner class, the instance of the inner class is not bound to the instance of the outer class, and is loaded only when it is called, which enables lazy loading. */    Private Static classsingletonholder{/*** Static initializers, which are guaranteed by the JVM for thread safety*/        Private StaticSingleton instance =NewSingleton (); }     Public StaticSingleton getinstance () {returnsingletonholder.instance; }}

Enumerate the Singleton classes:

Characteristics:

A simple, free-of-charge serialization mechanism, guaranteed by the JVM fundamentally, prevents multiple instantiations, and is a more concise, efficient, and secure way to implement a single case.

 Public enum Singleton {    /**     * Defines an enumerated element, which represents an instance of Singleton.      */         uniqueinstance;         /**      * The Singleton can have its own operation      */public     void  singletonoperation () {        // function processing     }}

A single-instance pattern of Java design patterns

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.