Singleton Lazy Loading Pattern

笑着哭i 提交于 2019-12-10 10:46:37

问题


I am trying to write a Singleton Lazy Loading Pattern. Here is the class:

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

I am wondering whether or not I am doing it in a right way?

Thanks in advance.


回答1:


I prefer to use enum for simplicity.

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



回答2:


That is correct. You may want to simplify the inner (holder) class as private static final IMDBLookup IMDB_LOOKUP = new IMDBLookup(); for brevity (to get rid of the static initializer block.)




回答3:


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

and you should probably use an enum (not completely sure I do this right)

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


来源:https://stackoverflow.com/questions/9347961/singleton-lazy-loading-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!