4

我正在使用 Gson 将 Json 反序列化为 model ApplicationModel。我希望这个模型是单例的,这样我就可以在我的应用程序的其他地方访问它。

现在,当 Gson 创建此类的一个实例时,我正在以一种非常规的方式创建单例实例。见下文:

public class ApplicationModel {

    private static ApplicationModel instance;

    private GeneralVO general;

    protected ApplicationModel() {
        instance = this;
    }

    public static ApplicationModel getInstance() {
        return instance;
    }

    public String getVersionDate() {
        return general.getVersionDate();
    }
}

这是我创建它并稍后在应用程序中重用它的方式:

InputStreamReader reader = new InputStreamReader(is);
ApplicationModel model1 = new Gson().fromJson(reader,ApplicationModel.class);

Log.i("MYTAG", "InputStream1 = "+model1.toString());
Log.i("MYTAG", "Date: "+model1.getVersionDate());
ApplicationModel model2 = ApplicationModel.getInstance();
Log.i("MYTAG", "InputStream1 = "+model2.toString());
Log.i("MYTAG", "Date: "+model2.getVersionDate());

这可以作为getInstance()返回相同的模型,但不知何故这似乎不正确。

我的问题是“这是一种很好的解决方法还是有更好的解决方案???”

编辑

做单例的更好方法是使用带有一个INSTANCE元素的枚举。

请参阅此帖子以获取说明

4

1 回答 1

1

我建议在您的模型上实例化您的单例实例,而不是使用构造函数实例化它。

public class ApplicationModel {

    private static ApplicationModel instance; //= new ApplicationModel(); 
    //instantiating here is called an "Eagerly Instantiated"

    private GeneralVO general;

    private ApplicationModel() { 
    }

    public static ApplicationModel getInstance() {
        //instantiating here is called "Lazily Instantiated", using : 
        //if (instance==null) {                  --> Check whether 'instance' is instantiated, or null
        //    instance = new ApplicationModel(); --> Instantiate if null
        //}
        return instance;  //return the single static instance
    }

    public String getVersionDate() {
        return general.getVersionDate();
    }
}

通过将构造函数设置为私有,您可以防止对象被另一个类重新实例化,要使用该对象,您必须使用ApplicationModel.getInstance().

因此,如果您想设置值,请调用ApplicationModel.getInstance().setterMethod(value),为什么这很有用?如果要跟踪更改,则只需要跟踪 setter 方法。如果你使用了构造函数,你也必须跟踪构造函数。

例子 :

// To SET the value:
// instead of ApplicationModel model1 = new Gson().fromJson(reader,ApplicationModel.class);
ApplicationModel.getInstance.setValue(new Gson().fromJson(reader,ApplicationModel.class);

// To GET the value :
ApplicationModel.getInstance.getValue();

“渴望实例化”与“延迟实例化”:

  • 如果您想要一种简单的方法来处理线程,那么 Eager 实例化很有用
  • 延迟实例化具有更好的内存占用

还有更多,你可以用谷歌搜索更多信息,但我认为这对你来说应该足够了。

希望这会有所帮助,祝你好运^^

问候,

里德

于 2013-09-20T03:20:40.233 回答