1

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?

singleton

  • Do you know about multithreading/concurrency issue if you modify a Singleton shared among threads ? – Walfrat Oct 9 '18 at 13:50
3

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.

|improve this answer|||||
1

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 newing 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.

|improve this answer|||||
  • 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? – Maicake Oct 9 '18 at 8:47
  • @Maicake you initialise your X somewhere above both ActivityA and ActivityB, and supply it to both. In the most extreme, that's main – Caleth Oct 9 '18 at 8:50
  • What does it mean above? My main activity is ActivityA I'm initializing it there. With supply you mean "dependency injection"? – Maicake Oct 9 '18 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. – Caleth Oct 9 '18 at 8:52
  • 1
    @Maicake yes, but "dependency injection" can be as simple as "constructor parameters" – Caleth Oct 9 '18 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.