单身懒惰加载模式

时间:2012-02-19 09:03:33

标签: java singleton lazy-loading

我正在尝试编写Singleton Lazy Loading Pattern。这是班级:

public class IMDBLookup {

    private static class LazyLoad {
        private static final IMDBLookup IMDB_LOOKUP;

        static {
            IMDB_LOOKUP = new IMDBLookup();
        }
    }

    public static IMDBLookup getInstance() {
        return IMDBLookup.LazyLoad.IMDB_LOOKUP;
    }
}

我想知道我是否以正确的方式做到了这一点?

提前致谢。

4 个答案:

答案 0 :(得分:2)

为了简单起见,我更喜欢使用枚举。

public enum IMDBLookup {
    INSTANCE;
    // add fields and methods here.
}

答案 1 :(得分:1)

这是正确的。为简洁起见,您可能希望将内部(holder)类简化为private static final IMDBLookup IMDB_LOOKUP = new IMDBLookup();(以摆脱静态初始化程序块。)

答案 2 :(得分:1)

public class IMDBLookup {

    private IMDBLookup(){
        // without this I do not get why is it a singleton
        // anyone could create instances of your class by the thousands
    }

    private static class LazyLoad {
        private static final IMDBLookup IMDB_LOOKUP;

        static {
            IMDB_LOOKUP = new IMDBLookup();
        }
    }

    public static IMDBLookup getInstance() {
        return IMDBLookup.LazyLoad.IMDB_LOOKUP;
    }
}

你应该使用枚举(不完全确定我这样做)

public class IMDBLookup {

    private IMDBLookup(){
    }

    private static enum LazyLoad {
        IMDB_LOOKUP_INSTANCE;
        private static final IMDB_LOOKUP = new IMDBLookup();
    }

    public static IMDBLookup getInstance() {
        return LazyLoad.IMDB_LOOKUP_INSTANCE.IMDB_LOOKUP;
    }
}

答案 3 :(得分:0)

关于克隆和序列化的建议

import java.io.Serializable;

public class DBConnectionInner implements Cloneable, Serializable {

    private static final long serialVersionUID = 1173438078175185035L;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return new CloneNotSupportedException("CLONE NOT SUPPORT FOR SINGTELTON");
    }

    protected Object readResolve() {
        return getInstance();
    }

    private DBConnectionInner() {}

    static DBConnectionInner getInstance() {
        System.out.println("DBConnectionInner getInstance");
        return LazyInit.instance;
    }

    public static class LazyInit {
        private static final DBConnectionInner instance = new DBConnectionInner();
    }

}