Reputation: 8350
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
.
Upvotes: 5
Views: 1851
Reputation: 7416
StinePike is right on this one, this is a very standard problem to encounter when coding. The Observer (or Listener in Java talk) pattern is the standard-practice solution to this. You should use your first proposition, which you worded kind of unclear, so I'll lay it out for you in case I'm not being too clear.
Let MyEventClass
offer a Listener interface, like MyEventClassListener
, and add/remove methods. Then MyClass
can attach/detach themselves as listeners. Here's a code example in case you need it:
MyEventClass.java
public class MyEventClass {
private Set<MyEventClassListener> listeners = new HashSet<MyEventClassListener>();
// Your code here...
public void addListener(MyEventClassListener listener) {
listeners.add(listener);
}
public void removeListener(MyEventClassListener listener) {
listeners.remove(listener);
}
public void notifyListeners() {
for (MyEventClassListener listener : listeners) {
listener.somethingHappened();
}
}
}
MyEventClassListener.java
public interface MyEventClassListener {
public void somethingHappened();
}
MyClass.java
public class MyClass implements MyEventClassListener {
MyEventClass myEventClass;
// Your code here..
public void someFunction() {
// Add as listener
myEventClass.addListener(this);
}
@Override
public void somethingHappened() {
// Act on callback
}
}
Upvotes: 0
Reputation: 54692
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
Upvotes: 3