Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Design pattern : Multiple event sources and One event Handler

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 :).

like image 376
Zakaria Avatar asked Jun 04 '10 16:06

Zakaria


1 Answers

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();
 }
}
like image 130
Justin Avatar answered Sep 28 '22 00:09

Justin