📙
Design Pattern
  • Introduction
  • 0. About Design Pattern
  • 1. Singleton
  • 1.1 Eager Singleton (a.k.a Pessimistic Lock Singleton)
  • 1.2 Lazy Singleton (a.k.a Optimistic Lock Singleton)
  • 1.3 理解Singleton
  • 1.4 Cache Singleton
  • 1.5 Extend Singleton
  • 1.6 Double Check and Lock Singleton
  • 1.7 Lazy Initialization Holder Class
  • 1.8 Enum Singleton
  • 1.9 Conclusion
  • 2. Factory
  • 2.1 Simple Factory
  • 2.2 Factory
  • 2.3 Abstract Factory
  • 2.4 Conclusion
Powered by GitBook
On this page

Was this helpful?

1.7 Lazy Initialization Holder Class

這很饒舌, 其實就是說還是有辦法可以同時做到延遲載入且thread safe的, 以下直接用範例說明:

package idv.design.pattern.singleton.laztinitholder;

/**
 * @author Carl Lu
 */
public class Singleton {

    private Singleton() {

    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }

    /*
     * An inner class that with no any binding relationship with outer class instance,
     * this class will be loaded only when invoked, so it can also reach the goal of lazy loading.
     */
    private static class SingletonHolder {
        /*
         * Initialize it statically and guaranteed thread safe by JVM
         */
        private static Singleton instance = new Singleton();
    }

}

這裡也只是在鋪梗而已, 真正讓人拍案叫絕的做法請見1.8小節.

Previous1.6 Double Check and Lock SingletonNext1.8 Enum Singleton

Last updated 5 years ago

Was this helpful?

原始碼

點我