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 appropria开发者_如何学Pythonte 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();
}
}
Sounds like an actor pattern to me. Each thread acts as an actor, accomplishing one single task. Th eoutcome is set on a queue (yes) to be processed by the next actor.
I have no experience with java actor frameworks, though. Consult Google for that.
In GWT, this is called the event bus. Either GWT.HandlerManager or GWTx.PropertyChangeSupport are Google recommended implementations. The latter is available in J2SE since 1.4.2
Maybe I don't understand your question, but I think you don't need any design pattern, but something from the java.util.concurrent package.
A ThreadPoolExecutor ?
Observable pattern doesn't have an opinion over threading. In EventThread pattern the listener can state in what thread and when is the event handled.
public class MyObservableObject {
...
void addListener(MyListener listener, Executor executor);
}
public interface MyListener {
void onEvent(Object sender, Object event);
}
// Example
obj.addListener( myListener, CURRENT_THREAD );
obj.addListener( myListener, myWorkQueue );
obj.addListener( myListener, AWT_EDT ); // or SWT_EDT
obj.addListener( myListener, Executors.newSingleThreadScheduledExecutor() );
精彩评论