Java design pattern: multiple event sources and one event handler

I want to implement a project in Java, where I have several sources of events (Threads). Such an event source performs a specific task and had to notify of a unique event handler (Class), and it needs to perform other tasks in accordance with the notification of event sources.

My question is: how to implement this desiqn appropriately in Java? Is there a design similar to this design?

Thanks in advance:).

+7
java multithreading event-handling design-patterns
source share
5 answers

I think you are looking for an Observer pattern. Java has some standard interfaces (java.util.Observer, java.util.Observable), although they are not of type; so you might think of 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(); } } 
+3
source share

I like the acting pattern. Each thread acts as an actor, performing one task. What you do is in line (yes), which will be processed by the next player.

I have no experience with Java frameworks. Consult Google.

0
source share

In GWT, this is called an event bus . Or GWT. HandlerManager or GWTx. PropertyChangeSupport Recommended Google Recommendations. The latter is available in J2SE from version 1.4.2

0
source share

Perhaps I do not understand your question, but I think that you do not need a design template, but something from java.util.concurrent .

A ThreadPoolExecutor?

0
source share

The observed pattern has no views on threads. In the EventThread Template, the listener can indicate in which thread and when the event is being processed.

 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() ); 
0
source share

All Articles