Java Reference
In-Depth Information
per InputSource . The trick here is to create a key and let that key be registered with the Router as the
InputChannel , instead of the “real” InputChannel .
The source calls the send method on the Router with two parameters: the key and the actual message. The
Router looks up the key and sends the message to the OutputChannels that it has just looked up.
Related Patterns
Related patterns include the following:
Mediator (page 77) - The Router is similar to the Mediator pattern. The difference is that the Mediator makes
decisions based on the content of the message and can therefore be application specific. The Router makes
decisions based on the source of the message.
Observer (page 94) - The Router pattern can be made more flexible by using the Observer pattern to allow
listeners to be registered.
WorkerThread (page 231) - The Worker Thread can be applied to the Router to increase the efficiency.
Example
Note:
For a full working example of this code example, with additional supporting classes and/or a RunPattern class,
see “ Router ” on page 540 of the “ Full Code Examples ” appendix.
The Router can be useful at various places in the example application. In almost every situation where there is
more than one interested party in any event, you can use the Router. The Router is essentially an implementation
of a listener structure; you will see some similarities.
The code for the Message class is shown here. It is a container for the source (an InputChannel ) and the actual
message—in this case, some String .
Example 4.25 Message.java
1. import java.io.Serializable;
2. public class Message implements Serializable{
3. private InputChannel source;
4. private String message;
5.
6. public Message(InputChannel source, String message){
7. this.source = source;
8. this.message = message;
9. }
10.
11. public InputChannel getSource(){ return source; }
12. public String getMessage(){ return message; }
13. }
Example 4.26 InputChannel.java
1. import java.io.Serializable;
2. public interface InputChannel extends Serializable{}
The OutputChannel is the interface that defines the method for sending the message to the target. Since the
OutputChannel can be used to communicate between machines, it is defined as a remote interface.
Example 4.27 OutputChannel.java
1. import java.rmi.Remote;
2. import java.rmi.RemoteException;
3. public interface OutputChannel extends Remote{
4. public void sendMessage(Message message) throws RemoteException;
5. }
The Router uses a hashmap to store links between the specific InputChannel and various OutputChannels .
When it receives a message, it looks up the destinations in its map.
Search WWH ::




Custom Search