1

I am building an Android guitar application and I need a way for GuitarString objects to notify multiple listeners that it has just been played. This includes the current Activity and all instances of GuitarStringView that have it as their GuitarString (the guitar is displayed twice, zoomed in & out).

I have so far handled this by having a ArrayList<OnPlayedListener> on GuitarString and each GuitarStringView or Activity adds themselves to that list. My Guitar class is a Singleton (which I know some may frown upon) so now I have to make sure objects remove themselves from the array of listeners when they're disposed of.

So my question is, is this a good approach, or is there a pattern that I should be using to handle this?

  • 3
    Observer pattern is very good for this. – Pieter B Jan 18 '14 at 16:31
  • Thank you, yes it looks ideal. If you make that your answer then I'll accept it – CrazyHorse Jan 18 '14 at 16:45
  • In good faith I can't make it an answer because I'm still learning about design patterns and was actually on the chapter that discussed the observer pattern, and the explanation was kinda exactly what you asked for. – Pieter B Jan 19 '14 at 3:00
  • @PieterB - Nonsense. You can certainly make it an answer--just because it is newly learned does not mean it is not appropriate to the question. – Matthew Flynn Jan 19 '14 at 6:59
1

Try the Observer Pattern, AKA publisher/subscribe (pubsub). It's exactly what you need here. Here is a great video of Derek Banas explaining how it works :

Observer Pattern Derek Banas

  • This would be a grade A+ answer with a little explanation/summary of what is described in the video. – Rig Jan 19 '14 at 22:29

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.