我想创建一个可以在整个程序中使用的静态对象。所以我有用于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
初始化,然后在程序的其余部分(活动)中使用? 最佳答案
您极有可能使此对象成为单例对象。
但是,问题在于初始化代码(在这种情况下为构造函数)中需要输入。这是对典型单例技术的挑战。
更好的方法是拥有一个静态初始化方法,该方法可以由当前调用构造函数的代码调用:
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()之前调用初始化方法。