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

标签 java android singleton

我想用下面的模式在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;
        }
}

但是当我想调用的私有(private)构造函数是

 private Singleton(Object stuff) {... }

如何将 stuff 传递给 INSTANCE = new Singleton()?如 INSTANCE = new Singleton(stuff);

重写上面的代码 fragment :

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

编辑:

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

我传入的对象是android应用上下文。

最佳答案

如果你真的想要一个单例,它应该只有一个实例(呃!)。如果您向 getInstance 添加参数,您可能希望返回的实例不同(否则不需要参数),这违背了目的。

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

public static final Singleton INSTANCE = new Singleton(getConfiguration());

其中 getConfiguration 返回所需内容(例如,无论是通过读取文件还是转发其他变量)。


常规免责声明:Singletons are evil .
其他资源:Google guide to writing testable code (如果您第一次不相信)。

关于java - 使用静态内部类创建java单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17839447/

相关文章:

android - 更新 Recyclerview 的项目计数

android - Robotium waitForFragment

java - 一项 Activity 中有 2 个 Action

java - 我可以忽略 "comparable"的使用吗

java - 理解 xml 模式定位

Java:序列化单例的实际用例?

java - java中可以有嵌套的单例吗?

java - 将单例用于不可变的无参数类不好吗?

java - Web应用程序中的时间戳更改问题

Java:构造函数中的 NULL