Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a listener for a Class instead of an instance

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.

like image 454
ilomambo Avatar asked Oct 21 '22 10:10

ilomambo


1 Answers

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

like image 52
stinepike Avatar answered Oct 27 '22 17:10

stinepike