I have a lot of instances of class MyClass
and they ALL have to react to some generated event from another class MyEventClass
. How should I do this?
My first thought was to define a listener in MyEventClass
and implement it in MyClass
, but this would require for every instance of MyClass
to set the listener, and in addition to define the listener as an array in MyEventClass
.
A lot of code/work.
Another option I thought is to use broadcast in MyEventClass
and receivers in MyClass
, but I am not sure, maybe is overkilling, and the receivers are to be registered as well (and unregistered on onStop()
)
A third option would be to define the listener implementation for the class MyClass
, not for each instance, this would fit perfectly, but I don't know if it is possible at all and how do I go about coding it.
Yet a fourth option I just came up with, is to implement the listener on the parent class of MyClass
and only setting this listener in MyEventClass
, then on the event occurrence loop through all MyClass
instances and manually call their listeners. This saves me registering each instance with MyEventClass
.
I think Observer design pattern
will be your best choice..
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems
with thousands of other links you can check these link1, link2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With