Singleton延迟加载模式

问题描述 投票:2回答:4

我正在尝试编写Singleton延迟加载模式。这是课程:

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;
    }
}

我想知道我是否以正确的方式来做?

提前感谢。

java singleton lazy-loading
4个回答
2
投票

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

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

1
投票

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


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;
    }
}

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();
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.