返回类的静态实例

时间:2016-03-01 10:43:07

标签: java static

我想创建一个静态对象,可以在整个程序中使用。所以我有这个类的sql。

private static FeadReadDB myInstance;

public FeadReadDB(android.content.Context context){
    super(context, DB_NAME, null, DB_VERION);
    myInstance = this;
}

public static FeadReadDB getInstance(){
    return myInstance;
}

首先,我没有这个getInstance函数,但是当我编写它并更改代码时,我得到了空指针异常。是否有可能创建这样的东西,比方说,在程序开始时初始化myInstance,然后在其余的程序(活动)中使用?

1 个答案:

答案 0 :(得分:1)

很可能,你的目的是使这个对象成为单身。 但问题是,初始化代码中需要输入(在本例中为构造函数)。这是对典型单例技术的挑战。

更好的方法是使用一个静态初始化方法,该方法可以被当前调用构造函数的代码调用:

public static void initialize(android.content.Context context) {
    FeadReadDB.myInstance = new FeadReadDB(context);
}

//The above will give you reasons to hide the constructor:
private FeadReadDB(android.content.Context context) {

    super(context, DB_NAME, null, DB_VERION);

    //As recommended, ensure that no one can call this constructor using reflection:
    if(null != myInstance) {
        throw new IllegalStateException("Cannot create multiple instances");
    }
}

//As the getter may be called before initialization, raise an exception if myInstance is null:
public static FeadReadDB getInstance(){
   if(null == myInstance) {
       throw new IllegalStateException("Initialization not done!");
   }

   return myInstance;
}

有了这个,你所要做的就是确保你的客户端代码在调用getInstance()之前调用初始化方法。

相关问题