Search code examples
javaswingobservers

Direct message based on content to different class


I have the following scenario:

I receive messages through a port (e.g. a serial COM port). Every message has a header which is used to check whom the message belongs to.

Let's assume the header is only one byte and this byte should be used to "forward" the message to an object.

One example:

Header -> Receiver
0x00 -> Object A
0x01 -> Object B
...

Currently I solved it in a way that I've an object who is e.g. owning the port to receive the messages (e.g. jSerialCom). Let's call this one the "port object". I made this one observable and every object who could be a receiver is observing it.

Once a message has been received the port object will inform all observer about the received message and they have to decide on their own if the message is related to them or not.

I have the feeling this is not the best solution and ask if you think that a better approach exists.


Solution

  • Have the port object maintain a map of observers. The map key is the [message] header byte and the map value is the list of observers who want to be notified when the port object receives a message with that header byte.