I've seen Singleton design pattern represented like below. Always with just getInstance() method. My doubt is: once I get the instance of the object I need, if I would like to modify it don't I need to add other methods to the Singleton class? Like setField( Type something) ? Or is against the pattern? In this case which is the right way to get a single instance and modify it?
2 Answers
The UML diagrams you find about design patterns usually only illustrate the bare minimum of what you need to have in order to implement the pattern. It usually does not include any "payload".
Your class which follows the Singleton pattern would of course require some instance methods which actually do something useful.
Firstly, the usual caveat: A singleton is a global variable (especially in languages where everything must be a member of a class). Global variables end up making your program harder to understand. You probably can do whatever you want to do via a singleton by just only new
ing your class once.
Yes, you are expected to have other members of your particular singleton type. Those are the members that are common to all singletons.
-
In my case I initialize an objectX in an ActivityA then the user click setting and go to ActivityB, here he modifies the preferences, and I want to take action on objectX from here. I saw (I'm new to Android) just two ways: have a single instance of objectX or passing around its reference all the way to ActivityB (but I couldn't find concrete code to do it, because with intent you can just pass simple-type). Also with common to all singletons you mean like setters and getters?– MaicakeOct 9, 2018 at 8:47
-
@Maicake you initialise your
X
somewhere above bothActivityA
andActivityB
, and supply it to both. In the most extreme, that'smain
– CalethOct 9, 2018 at 8:50 -
What does it mean above? My main activity is ActivityA I'm initializing it there. With supply you mean "dependency injection"?– MaicakeOct 9, 2018 at 8:50
-
@Maicake no, I mean the definition of a singleton is any type with those members. This is because the access restriction on construction ensures there is only ever one instance.– CalethOct 9, 2018 at 8:52
-
1@Maicake yes, but "dependency injection" can be as simple as "constructor parameters"– CalethOct 9, 2018 at 8:53