GOF23 in Java (23 design mode)---------Singleton mode (Singleton)

Source: Internet
Author: User

GOF23 in Java (23 design mode)---------Singleton mode (Singleton)

  In the Java this language, its advantage lies in its own portability above, and to be portable, it needs an intermediary as a translation work, in order to achieve local and Java unity, but in this case it is a considerable consumption of resources, so Java programmers need to constantly optimize their own code. The singleton pattern studied today is produced under these conditions,

The so-called Singleton pattern, there is only one instance, in the heap there is only one. If we have an example, we need one, but we will use it many times, and then there will be awkward problems.

Like what:

    1. The TaskManager (Task Manager) of Windows is typical of just one instance,
    2. Windows Recycle (Recycle Bin) in the system, the Recycle Bin only maintains one instance
    3. In our project, the class that reads the configuration file is often used,
    4. Website counters, generally also use a singleton mode, otherwise difficult to achieve synchronization
    5. Database connection pool design generally also uses singleton mode, because database connection is a kind of database resource
    6. Operating system's file system, because an operating system can have only one file system
    7. Application is also a singleton mode
    8. In spring, each bean is a singleton by default, and the advantage of this is that the spring container can manage
    9. In servlet programming, each servlet is also a singleton
    10. In spring mvc/struts 1, the control objects used are also single-instance

    In the above we learned that the singleton pattern in our project, almost every day, so here, we study carefully, this design pattern of how to achieve the best (when it comes to implementation, it is realized that most of us only know there are two, while there are three patterns know not many people, and the use of deserialization, Reflection vulnerability to forced release of single case)

  • a hungry man mode
    • Use the static property to persist an object's singleton pattern, but must be loaded when the class is loaded, so there is no delay in instantiating the performance
      * And in the object that gets the instance, there is no synchronization lock on the resource, so the call is efficient
      * While using the JVM ClassLoader, the JVM's underlying nature is thread-safe,
    • Advantage: High thread safety call rate
    • Cons: Cannot delay loading
      1  Public classEager_singleton {2 3     Private StaticEager_singleton Singleton =NewEager_singleton ();4     5     PrivateEager_singleton () {}6     7      Public StaticEager_singleton newinstance () {8         returnSingleton;9     }Ten}
  •   Lazy mode 
    • still use the static property to maintain the object's singleton mode, but in the method new out, when we go to adjust the method, then to load, is lazy, lazy to load, but because of the instantiation in the method, so we have to use the concept of the lock on the method to synchronize with him, if not lock, then we are in the a thread to remove the use of it and in the B thread to call it he is not a concept
      • Pros: Can be delayed loading, and threads are safe
      • Disadvantage: The method realizes the synchronization, so the utilization ratio of resources is low.
/*** Lazy Single case mode *@authorLiu Acid **/ Public classSluggard_singleton {Private StaticSluggard_singleton Singleton =NULL; PrivateSluggard_singleton () {} Public synchronized StaticSluggard_singleton newinstance () {if(Singleton = =NULL) {Singleton=NewSluggard_singleton (); }        returnSingleton; }}

    • Double-detector
      • Place the code underneath the sync block inside the IF
      • Problems: Due to compiler optimizations and other reasons, the JVM's underlying internal model is occasionally problematic and is not recommended for use.

     

/*** Double check lock for single case mode *@authorLiu Acid **/ Public classDoublecheck_singleton {Private StaticDoublecheck_singleton instance =NULL;  Public StaticDoublecheck_singleton getinstance () {if(Instance = =NULL) {Doublecheck_singleton sc; synchronized(Doublecheck_singleton.class) {SC=instance; if(sc = =NULL) {           synchronized(Doublecheck_singleton.class) {             if(sc = =NULL) {SC=NewDoublecheck_singleton (); }} instance=SC; }       }     }     returninstance; }   PrivateDoublecheck_singleton () {}}
    • Static inner class method implementation

      • This approach is combined with the advantages of lazy and a hungry man-

     

/*** Test static inner class implementation Singleton mode * This way: thread safety, high efficiency, and delay loading! * @authorLiu Acid **/ Public classstaticinnerclass{Private Static classstaticinnerclass{Private Static FinalStaticinnerclass instance =NewStaticinnerclass (); }        PrivateStaticinnerclass () {}//method is not synchronized, the call efficiency is high!      Public Staticstaticinnerclassgetinstance () {returnstaticinnerclass.instance; }    }

    • Enumeration implementation
      • Inside the Java JVM is a natural singleton pattern, which is the enumeration type, which is protected by the JVM's underlying if the enumeration type is used
        • For example, using deserialization, and using reflection, cannot break this principle.

      • Pros: Appeal

      • Cons: Cannot delay loading

    

/**@author*/publicenum  enum_singleton{         // This enumeration element is itself a singleton!      INSTANCE;         // Add the actions you need! public    void  xxxxx () {    }    }

    • How to prevent deserialization, reflection broken-loop Singleton mode (except enumeration)
      • In reflection, if we call a private constructor, we throw an exception, but someone will skip the legal check so that it can access our private constructor.
ImportJava.lang.reflect.Constructor;/*** Test reflection and deserialization cracking Singleton mode *@authorLiu Acid **/ Public classmain{ Public Static voidMain (string[] args)throwsException {//invoking a private constructor directly by means of reflectionClass<singleton> clazz = (class<singleton>) class.forname ("Com.suansuan.singleton.Singleton"); Constructor<Singleton> C = Clazz.getdeclaredconstructor (NULL); //Skip a legal checkC.setaccessible (true); Singleton S1=c.newinstance (); Singleton S2=c.newinstance ();        System.out.println (S1); SYSTEM.OUT.PRINTLN (S2);
}
}
    • When deserializing, we also cannot get an object, so the following code solves both of these problems
      /*** Test Lazy Singleton mode (how to prevent reflection and deserialization of the vulnerability) *@authorLiu Acid **/ Public classSingletonImplementsSerializable {//when the class is initialized, the object is not initialized (deferred loading, which is created when it is actually used).     Private StaticSingleton instance; PrivateSingleton () {//Privatization Constructor//reflection, we do the following to circumvent, skip the legitimate detection of illegal access        if(instance!=NULL){            Throw Newruntimeexception (); }    }        //method synchronization, the call efficiency is low!      Public Static  synchronizedSingleton getinstance () {if(instance==NULL) {instance=NewSingleton (); }        returninstance; }        //when deserializing, the object specified by this method is returned directly if Readresolve () is defined. You don't need to create new objects alone!     PrivateObject Readresolve ()throwsobjectstreamexception {returninstance; }    }

Summary: Use enumerations to replace a hungry man, use static inner classes instead of lazy-type

The first time to write a blog, thank you if you have the wrong room point, we progress together, common development, thank you

    

GOF23 in Java (23 design mode)---------Singleton mode (Singleton)

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.