使用静态内部类创建java单例

Cot*_*nyo 1 java singleton android

我想使用以下模式在java中创建单例

public class Singleton {
        // Private constructor prevents instantiation from other classes
        private Singleton() { }

        /**
        * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
        * or the first access to SingletonHolder.INSTANCE, not before.
        */
        private static class SingletonHolder { 
                public static final Singleton INSTANCE = new Singleton();
        }

        public static Singleton getInstance() {
                return SingletonHolder.INSTANCE;
        }
}
Run Code Online (Sandbox Code Playgroud)

但是当我想调用的私有构造函数发生时会发生什么

 private Singleton(Object stuff) {... }
Run Code Online (Sandbox Code Playgroud)

我怎么传递stuffINSTANCE = new Singleton()?如在INSTANCE = new Singleton(stuff);

重写上面的代码段:

public class Singleton {
        // Private constructor prevents instantiation from other classes
        private Singleton(Object stuff) { ... }

        /**
        * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
        * or the first access to SingletonHolder.INSTANCE, not before.
        */
        private static class SingletonHolder { 
                public static final Singleton INSTANCE = new Singleton();
        }

        public static Singleton getInstance(Object stuff) {
                return SingletonHolder.INSTANCE;//where is my stuff passed in?
        }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

对于那些声称此模式不是线程安全的人,请阅读:http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh.

我传入的对象是android应用程序上下文.

ass*_*ias 5

如果你真的想要一个单身,那么它应该只有一个实例(呃!).如果你向你添加一个参数,getInstance可能希望返回的实例不同(否则就不需要参数),这会使目的失败.

如果您的目标是在创建唯一实例时添加一些配置,最简单的方法是在实例化时对配置信息进行单例查询:

public static final Singleton INSTANCE = new Singleton(getConfiguration());
Run Code Online (Sandbox Code Playgroud)

其中getConfiguration返回所需内容(例如,通过读取文件或转发其他变量).


通常的免责声明:单身人士是邪恶的.
其他资源:Google编写可测试代码的指南(如果您第一次不相信).