1

I have an Application with a List of Objects on the main screen. When clicking on one of them, I'm transferring the user to the next Fragment.
Then I have more 3 Fragments which are setting(manipulating) the object fields. My question is, is it right instead of implementing the Serializable interface and pass the Object using Bunde I'll do kind of Singleton. Something like this (I know that for Singleton I must do the empty constructor private).

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

        );

I test it, it works great, but my question is, is it right to do so and what if it can cause problems in the futere?

Igor Fridman
  • 1,267
  • 1
  • 16
  • 30
  • Not clear, where are you using `Serializable`? – Alexandre Dupriez Aug 05 '18 at 10:12
  • Hi @Alexandre Dupriez. I'm not using yet. That actually my question, use the approach that you see above or use Serializable and pass the object in Bundle. – Igor Fridman Aug 05 '18 at 10:14
  • I am not sure I understand your use case, but at a high-level, if `Father` is a data object, singleton does not seem the right pattern. If you serialise your object, you will end up with a copy of the `Father` instance. One question is which instance of `Father` do you need to update? – Alexandre Dupriez Aug 05 '18 at 10:18
  • Maybe [this question](https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons#comment78107_137975) can help. – Mr.O Aug 05 '18 at 11:20

0 Answers0