Curriculum design patterns Design patterns succinctly 8-5 singleton design pattern - hungry Chinese-style

1 to explain the code

1.1 starving type does not appear multithreading issues

1.2 advantages and disadvantages

 

2 Code Walkthrough

2.1 Code drill 1 (starving formula)

2.2 Code drill 2 (block static manner)

 

 

 

1 to explain the code
1.1 starving type does not appear multithreading issues

At the beginning of loading the initialization is complete, to avoid the thread synchronization problem,

 

1.2 advantages and disadvantages

Pros: At first load initialization is complete, to avoid the thread synchronization issues.

Disadvantages: If the class does not often use, more consumption of resources, resulting in wasted memory.

 

2 Code Walkthrough
2.1 Code drill 1 (starving formula)
Package Penalty for com.geely.design.pattern.creational.singleton; 

public  class HangrySingleton { 


    / ** 
     * declare private constants, initialized when the class had been assigned up. Hungry Chinese-style class initialization when loaded only once. 
     * It does not exist multi-threading problems. Lazy man not declared final, because it is not loaded when the class is initialized good. 
     * / 
    Private  Final static HangrySingleton hangrySingleton = new new HangrySingleton (); 

    / ** 
     * declare a private constructor 
     * / 
    Private HangrySingleton () { 

    } 

    / ** 
     * provide an external interface to obtain the object 
     * @return 
     * / 
    public HangrySingleton the getInstance () {
         return hangrySingleton; 
    } 
}

 

2.2 Code drill 2 (block static manner)
Package Penalty for com.geely.design.pattern.creational.singleton; 

public  class HangrySingleton { 


    / ** 
     * declare private constants, initialized when the class had been assigned up. Hungry Chinese-style class initialization when loaded only once. 
     * It does not exist multi-threading problems. 
     * / 
    Private  Final  static hangrySingleton HangrySingleton; 

    static { 
        hangrySingleton new new HangrySingleton = (); 
    }

     / ** 
     * declare a private constructor 
     * / 
    Private HangrySingleton () { 

    } 

    / ** 
     * provide an external interface to obtain the object 
     * @return 
     * / 
    public the getInstance hangrySingleton () {
         return hangrySingleton;  
    }
}

 

Guess you like

Origin www.cnblogs.com/1446358788-qq/p/11369042.html