I want to implement a design in Java where I have multiple event sources (Threads). Such event source accomplish a specific task and had to notify the unique Event Handler (Class) and this one have to accomplish other tasks according to event sources notifications.
My question is : how to implement this desiqn in the appropriate manner in Java? There is a design pattern similar to this design?
Thank you in advance :).
I think you are looking for the Observer pattern. Java does have some standard interfaces (java.util.Observer, java.util.Observable), though these are not type specific; so you might consider your own if the domain seems to require it.
class MyThread implements Runnable {
Observable observable;
public MyThread(EventHandler observer) {
observable = new Observable();
observable.addObserver(observer);
}
public void run() {
while (!done()) {
Object result = doStuff();
observable.notifyObservers(result);
}
}
}
// might have this be singleton
class EventHandler implements Observer {
public synchronized void update(Observable o, Object arg) {
accomplishOtherTask();
}
}
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