Create a design pattern (five) Singleton

First, a word background

If the company has a printer, we want to use it, but could not bring him home, of course, just because there is no need to print documents while he occasionally buy at home, this printer can be viewed as a single example, the following to analyze

Second, the use of scenarios

When you want to control the number of instances, to save system resources.

Third, the model analysis

The company's printer: singleton object

Buy their own home printer: a new instance of an object

Fourth, code analysis

1. lazy type, thread safe

Are Lazy Initialization: is

Are multi-thread safe: No

Achieve Difficulty: Easy

Description: This is the most basic way of implementation which achieved the biggest problem is not support multi-threading. Because there is no lock synchronized, so strictly speaking it is not a singleton.
Obviously this way lazy loading, does not require thread-safe, it can not work in multi-threaded properly.

/ ** 
 * 1, lazy type, thread-safe 
 * / 
public  class SingletonOne {
     Private  static SingletonOne instance; 

    Private SingletonOne () { 
    } 

    // no synchronization lock 
    public  static SingletonOne the getInstance () {
         IF (instance == null ) { 
            instance = new new SingletonOne (); 
        } 
        return instance; 
    } 
}

 

2, lazy style, thread-safe

Are Lazy Initialization: is

It is multi-thread safe: is

Achieve Difficulty: Easy

Description: in this way have a good lazy loading, can work well in multi-thread, however, is very low efficiency, 99% of cases does not require synchronization.
Pros: The first call was initialized, to avoid wasting memory.
Cons: Must be locked synchronized to ensure a single case, but the lock will affect the efficiency.
Performance getInstance () the application is not critical (which use less frequently).

/ ** 
 * 2, lazy type, security thread 
 * / 
public  class SingletonTwo {
     Private  static SingletonTwo instance; 

    Private SingletonTwo () { 
    } 

    // synchronization method applied to the lock, such that the external synchronization mechanism to follow the call 
    public  static  the synchronized SingletonTwo the getInstance () {
         IF (instance == null ) { 
            instance = new new SingletonTwo (); 
        } 
        return instance; 
    } 
}

 

3, hungry Chinese style

Are Lazy Initialization: No

It is multi-thread safe: is

Achieve Difficulty: Easy

Description: In this manner commonly used, but prone garbage objects.
Advantages: not locked, the efficiency will improve.
Disadvantages: initialized when the class is loaded, wasting memory.
It is based classloader mechanism avoids the synchronization problem multithreading, however, instance to instance of the class is loaded at the time, although there are causes class loading are many, most of them in singleton mode are calling getInstance method, but it can not be determined there are other ways (or other static methods) leads the class loader, which apparently did not reach instance initialization lazy loading effect.

/ ** 
 * 3, starving the formula 
 * / 
public  class SingletonThree {
     // initialized when the class object is loaded (based on the synchronization mechanism avoids classloader multithreading, the loadClass classloader type lock) 
    Private  static SingletonThree instance = new new SingletonThree ( ); 

    Private SingletonThree () { 
    } 

    public  static SingletonThree the getInstance () {
         return instance; 
    } 
}

4, double lock detection / double checking lock (the DCL, i.e., double-checked locking)

JDK version: JDK1.5 from

Are Lazy Initialization: is

It is multi-thread safe: is

Realize the difficulty: more complex

Description: This dual mode locking mechanism, and in safe multithreading can maintain high performance.
Performance getInstance () is critical to the application.

/ ** 
 * 4, double lock detection / double checking lock (the DCL, i.e. the checked-locking Double) 
 * / 
public  class SingletonFour {
     // volatile key role as a command, to ensure that this directive is not optimized by the compiler omitted, multithreading prevent multiple local calls Singleton 
    Private  volatile  static SingletonFour Singleton; 

    Private SingletonFour () { 
    } 

    public  static SingletonFour getSingletonFour () {
         IF (Singleton == null ) {
             // Singleton initialization lock 
            the synchronized (SingletonFour . class ) {
                 IF (Singleton == null ) { 
                    Singleton= new SingletonFour();
                }
            }
        }
        return singleton;
    }
}

5, register-based / static inner classes

Are Lazy Initialization: is

It is multi-thread safe: is

Realize the difficulty: General

Description: in this way can achieve the same effect double check the lock mode, but the implementation is simpler. Initialization of the static field using a delay, this mode should be used instead of double lock detection mode. This embodiment applies only to the static field, the double lock detection mode can be used when a delay required to initialize instance fields.
In this way the use of the same classloader mechanisms to ensure that only one thread at initialization instance, it is now the third ways are different: The first three ways as long as the Singleton class is loaded, the instance is instantiated (not reached lazy loading effect), but this approach is being loaded Singleton class, instance may not be initialized. Because SingletonHolder class is not actively used, only through explicit call getInstance method will explicitly load SingletonHolder class to instantiate instance. Imagine, if you instantiate instance is resource-consuming, so want it to delay loading, on the other hand, do not want to load when the class is instantiated Singleton, Singleton class because they can not ensure that the initiative may also be used in other places in order to be loaded, this time to instantiate instance clearly inappropriate. This time, in this way compared to the first three kinds of ways it is very reasonable.

/ ** 
 * 5, register-based / static inner class 
 * / 
public  class SingletonFive {
     / * 
    Causes privatization inner class: 
     1. SingletonFive generated object privatization 
     2. If instantiated instance is resource-consuming, so want it lazy loading, 
       on the other hand, do not want to instantiate in the Singleton class loaders, 
       because they can not ensure Singleton class may also be loaded so as to be actively used in other places, 
       so this time is instantiated instance clearly inappropriate, so put a privatization inner class which, when used to go and call initialization. 
    * / 
    Private  static  class SingletonFiveHolder {
         Private  static  Final SingletonFive INSTANCE = new new SingletonFive (); 
    } 

    Private SingletonFive () { 
    } 

    public  static  Final SingletonFive getInstance() {
        return SingletonFiveHolder.INSTANCE;
    }
}

6, enumerate

JDK version: JDK1.5 from

Are Lazy Initialization: No

It is multi-thread safe: is

Achieve Difficulty: Easy

Description: This implementation has not been widely adopted, but this is the best way to achieve single-mode embodiment. It is more compact, automatic support serialization mechanism to prevent multiple instances of the absolute.
This approach is advocated Effective Java author Josh Bloch way, it can not only avoid multi-thread synchronization problems, but also automatically supports serialization mechanism to prevent deserialization re-create a new object, absolutely prevent multiple instantiation. However, only joined the enum properties after JDK1.5, write in this way can not help but feel strange, in practice, rarely used.
Not by reflection attack to call the private constructor.

/ ** 
 * 6, the enumeration 
 * / 
public  enum SingletonSix {
     // INSTANCE actually represents an enumeration object, SingletonSix instance = SingletonSix.INSTANCE; you can call to 
    INSTANCE; 

    public  void whateverMethod () { 
    } 
}

 

 

 

Guess you like

Origin www.cnblogs.com/riches/p/11221041.html