1

Building an android app that displays a list of of Dog objects in Activity A. When you a tap a Dog in the list, that single dog is accessed by Activity B, Fragment B, and 3 other classes.

After that Dog is modified, it gets passed to Activity C and Activity D that all modify it, before finally making a network request.

Currently, I pass the same instance of Dog back and forth through activities, fragments, and classes using callbacks, parcelable extra in intents, and bundles for fragments. This is getting really messy really fast. Is using a Singleton a good idea in this situation?

If Dog were a singleton, how can I load multiple Dogs to begin with?


Think of the list of Dogs as a list of empty boxes. After a single Dog is selected, it goes through a conveyer belt of Activities, Fragments, and helper Classes, where the box gets filled with data. At the end of the user flow, this box is filled up with a bunch of information, ready to be shipped off to the backend server.

Robert Harvey
  • 200,592
aaa
  • 139

3 Answers3

1

I don't think that you should use a singleton pattern in this case. So if you implement the Singleton correct, there is only one instance for the dog class. If you have a list with dogs, it's not possible for you to implement a singleton if you don't want to show the same dog in every line. So you have a reference to the dog like this Dog dog = Dog.getInstance();

Everytime you access the getInstance Method, the singleton will return you this one Object. Everything you change, is changed in this one object. So if you want to have more than one Dog, the Singleton pattern isn't the right way for you!

Gulliva
  • 111
0

Should a singleton be used in the following case?

No, seems like it wouldn't work.

Perhaps you have a new responsibility that you should create its own class for - namely that of having a selected dog and the moving of it through the activities. The selected dog would be a member of that class, i.e. some fixed state per instance object, for all methods (of that class) to work on (and without using the singleton pattern).

With that perhaps you can have different dogs in different flows in parallel.

Erik Eidt
  • 34,819
0

Nothing in your description implies a need to limit Dog to a single object. This suggests that doing OOP gymnastics to ensure you don't end up with two Dogs at the same time is not a good idea. How could two Dogs possibly crash or corrupt your program in the scenario you describe?

Singleton is usually a bad design pattern to begin with. Keep in mind that design patterns are generalized solutions for OOP languages in cases where the language itself is unable to handle the situation naturally. When you use a design pattern, you usually do it because you don't have a more natural solution.