单身人士与params

时间:2014-11-04 10:44:37

标签: java parameters singleton

我已经写了一个Singleton,但是这个单例需要一个Context作为初始化自己的参数。由于Context在其构造函数中只使用一次,我不想在getInstance(Context)中添加它。经过多思考后,我得出了以下答案:

public class Singleton {
    private static Context sContext;

    public static void init(Context context) {
        sContext = context;
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static Singleton INSTANCE = new Singleton();
    }

    private Singleton() {
        if (sContext == null) {
            throw new IllegalArgumentException("#init should be called in Application#onCreate");
        }
        // Initialize the Singleton.
        // .....
        // After the constructed, remove the sContext.
        sContext = null;
    }
}

很好,在Android / Applicaiton#onCreate方法中调用了类方法init。 它不是SingletonHolder.INSTANCE的实例,因为它没有加载。 有人可以就我的解决方案向某人提出建议。谢谢!

在@ WarrenFaith的帮助下,我改变了我的代码。

 public class Singleton {

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static Singleton INSTANCE = new Singleton();
    }

    private Singleton() {
        final Context context = BaseApplication.getApplication();
        // Initialize the Singleton.
        // .....
    }
}

public class BaseApplication extends Application {

    private static Application sApplication;

    public static Application getApplication() {
        return sApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sApplication = this;
    }
}

1 个答案:

答案 0 :(得分:0)

为什么不使用更方便的解决方案:

public class Singleton {
    private final static Singleton mInstance = new Singleton();
    private final static Context sContext;

    private Singleton() {
        sContext = MyApplication.getInstance();
        // do more
    }

    public static Singleton getInstance() {
        return mInstance;
    }
}

这是一个非常防弹的单身人士模式。

当然,您需要将应用程序类实现为单例,但根据定义它已经是。

public class MyApplication extends Application {
    private static MyApplication mInstance;

    @Override
    protected void onCreate() {
        super.onCreate();
        mInstance = this;
        // create your Singleton!
        Singleton.getInstance();
    }

    public static MyApplication getInstance() {
        return mInstance;
    }
}