Design Mode: Singleton Mode

Source: Internet
Author: User

Design Mode: Singleton Mode

 

 

Creational Model

 

The generation of objects consumes system resources, so how to efficiently produce, manage, and operate objects has always been a topic worth discussing. The Creational model is related to the establishment of objects, the pattern under this classification provides some guiding principles and design directions. The list below all belongs to the Creational model.

  • Simple Factory mode Abstract Factory mode Builder mode Factory Method mode Prototype mode Singleton mode Registry of Singleton Mode

    When the program requires only one Singleton, you need to use the singleton mode. Without this requirement, you do not need to use the singleton mode.

    Lazy and hungry

    Let's take a look at two common Singleton models: lazy and hungry.

    // Lazy public class SingletonLazy {private static SingletonLazy single = null; private SingletonLazy () {} synchronized public static SingletonLazy getInstance () {if (single = null) {single = new SingletonLazy ();} return single ;}// hungry Chinese public class SingletonHunger {private static SingletonHunger single = new SingletonHunger (); private SingletonHunger () {} public static SingletonHunger getInstatnce () {return single ;}}

     

    Note that the lazy Singleton class uses synchronization for static factory methods to process multi-threaded environments.

    Optimized Chinese Style

    In fact, the singleton mode is very simple, but it involves a lot of knowledge that is very complicated. for example, although the hungry Chinese Style solves the problem of multi-thread security and does not need to use synchronization (improving efficiency), it wastes memory because the SingletonHunger class initializes the object during loading, in this case, we can use the internal class mechanism to solve this problem.

    public class SingletonInner {    private static InnerInstance{        private static SingletonInner single = new SingletonInner() ;    }    private SingletonInner(){    }    public static SingletonInner getInstance(){        return InnerInstance.single ;    }}

     

    The above Code involves a lot of knowledge.

    1. The internal class declaration is static: it can be used without initializing the external class. The internal class is loaded and initialized only when it is used by itself, but its internal class is not initialized. for details, see when the class is loaded or when the class is loaded. First, when the class object is generated, the class and all its parent classes will be loaded. Second, when accessing the static members of the class; third: class. forName (Class Name); optimized lazy

      We know that lazy has saved space, but it uses synchronization to solve thread security problems, greatly reducing program efficiency.

      So we thought about how to improve the efficiency of the lazy style. First, it still needs to be synchronized.

      One way isDual Check MechanismThis is widely used in C language, but it is wrong in java. If you lock the basic type, there is no problem, however, if you are locking an object, there will be problems. but here we talk about the singleton mode, so the lock must be an object instead of int, long, double, and other data types.

      The following code is incorrect.

      public class SingletonLazy01 {    private static SingletonLazy01 single = null ;    private SingletonLazy01(){    }    public static SingletonLazy01 getInstance(){        if(single == null){            synchronized(SingletonLazy01.class){                if(single == null){                    single = new SingletonLazy01() ;                }            }        }        return single ;    }}

       

      We use the volatile keyword

      public class SingletonLazy01 {    private volatile static SingletonLazy01 single = null ;    private SingletonLazy01(){    }    public static SingletonLazy01 getInstance(){        if(single == null){            synchronized(SingletonLazy01.class){                if(single == null){                    single = new SingletonLazy01() ;                }            }        }        return single ;    }}

       

      For the dual-check issue, see here ---> dual-check locking and delayed Initialization

      19:52:59

      Brave, Happy, Thanksgiving!

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.