Java Design Pattern Singleton mode (Singleton)

Source: Internet
Author: User

Objective:

In summing up the okhttp, in order to manage the network request to use the singleton mode, the night is really no state, calm down to learn to summarize the use of the most frequently used design mode single-case mode.

Single-Case mode:

Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system.

Single Case features:
    • A singleton class can have only one instance.
    • The Singleton class must create its own unique instance.
    • The Singleton class must provide this instance to all other objects.
Single-Case classification: 1). Lazy Single Case

(1) Non-thread safe implementation

 public  class    Singleton {  Singleton () {}  private  static<         /span> Singleton instance;  public  static   Singleton getinstance () { if  (instance = null  ) {instance  = new  
    
      Singleton ();         
     return   instance; }     } 

(2) Thread safety Implementation mode One method plus synchronous this implementation is inefficient

 Public classSingleton {PrivateSingleton () {}Private StaticSingleton instance;  Public Static synchronizedSingleton getinstance () {if(Instance = =NULL) {instance=NewSingleton (); }       returninstance; }     }

(3.) Thread safety Implementation mode two double check lock

 Public classsingleton{Private StaticSingleton single;//declaring a static variable for a singleton object  PrivateSingleton () {}//Private Construction Methods   Public StaticSingleton Getsingle () {//externally the object can be obtained by this method    if(single =NULL){             synchronized(Singleton.class) {//ensures that only one object can access this synchronization block at a time            if(single =NULL) { single=NewSingleton (); }             }      }        returnSingle//return to the created object  }  }  
2.) A hungry man type single case class

A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is inherently thread-safe.

 Public class Singleton  {      private  Singleton () {      }      privatefinalstatic New Singleton ();       Private Static Singleton getinstance () {          return  instance;      }  

3.) Internal class-Type singleton class

In the inner class, deferred loading is implemented, only we call the getinstance (), Only the unique instance is created in memory. It also solves the problem of multi-threading in lazy-type. The solution is to take advantage of the ClassLoader features to achieve thread safety and avoid the performance impact of synchronization.

 Public class singleton{             private  Singleton () {           }         privateclass  Singletonholedr () {             privatestaticnew  Singleton ();         }          Private Static Singleton getinstance () {             return  singletonholedr.instance;         }     
4.) Enumeration Class Singleton

"Effective Java" authors recommend the method, the advantage: not only to avoid multi-threaded synchronization problems, but also to prevent deserialization re-create new objects

 Public enum Singleton {    /**     * Defines an enumerated element, which represents an instance of Singleton.      */         uniqueinstance;         /**      * The Singleton can have its own operation      *    /publicvoid  dosomething () {         // function processing     }}
5.) The difference between lazy and a hungry man

(1) Initialization angle

A hungry man is the class once loaded, the singleton initialization to complete, to ensure that the getinstance time, the singleton is already exist, and idle lazy, only when the call getinstance, only to go back to initialize this singleton

(2) Thread Safety angle

A hungry man-style is inherently thread-safe, can be used directly for multithreading without problems, lazy-type itself is non-thread-safe, need to implement thread-safe methods.

Java Design Pattern Singleton mode (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.