Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了android – 使用Gson将Json反序列化为单例大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Gson将Json反序列化为模型ApplicationModel.我希望这个模型是一个单例,@R_199_9447@在我的应用程序的其他地方访问它.

现在,当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元素的枚举.

See this post for an explanation

@L_450_10@

我建议在Model上实例化你的单例实例,而不是使用构造函数实例化它.

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();
    }
}

通过将构造函数设置为private,可以防止对象被另一个类重新实例化,要使用该对象,您必须使用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 Instantiation非常有用@H_419_54@主题@H_419_54@> Lazy Instantiation具有更好的内存占用

除此之外,您可以谷歌搜索更多信息,但我认为这对您来说应该已经足够了.

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

问候,

里德

大佬总结

以上是大佬教程为你收集整理的android – 使用Gson将Json反序列化为单例全部内容,希望文章能够帮你解决android – 使用Gson将Json反序列化为单例所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。