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小節.
Last updated
Was this helpful?