首页 > 解决方案 > 使用可序列化或修改的单例?

问题描述

我在主屏幕上有Application一个ListObjects单击其中一个时,我将用户转移到下一个Fragment.
然后我有更多 3 个Fragments正在设置(操作)对象字段。我的问题是,它是否正确,而不是实现Serializable interface并通过Object使用 Bunde 我会做一种 Singleton。像这样的东西(我知道对于单例我必须将空构造函数设为私有)。

public class Father {


    private static Father instance;
    private String name;
    private int age;



    Father() {
    }


    public static Father getInstance(Father father) {
        if (instance == null) {
            instance = new Father();
            if(father != null) {
                instance = father;
            }
        }

        return instance;
    }



       Father regularFather = new Father();
        regularFather.setAge(35);
        regularFather.setName("Danny");

        Father regularFather2 = new Father();
        regularFather2.setAge(44);
        regularFather2.setName("Mike");

        Father regularFather3 = new Father();
        regularFather3.setAge(15);
        regularFather3.setName("Tom");

       Father.getInstance(regularFather2).setName("Mike32");


 System.out.println("regularFather name is: " + regularFather.getName()
                + " \n regularFather2 name is: " + regularFather2.getName()
                + " \n regularFather3 name is: " + regularFather3.getName()
                + " \n Instance name is: " +  Father.getInstance(null).getName()

        );

我对其进行了测试,效果很好,但我的问题是,这样做是否正确,如果它会在未来引起问题怎么办?

标签: javaandroidserializationsingletonserializable

解决方案


推荐阅读