I have a specialized object class that sends messages to its components so that they can change themselves as needed. The object class allows me to mix and match components so that I can have different objects with similar functionality without having a huge inheritance tree. (I think this is called the component pattern.) Here’s what I want to do:
//MyObject.java
public class MyObject {
private HashSet<MyComponent> components_;
void send(Message message) {
for (MyComponent component : components_) {
component.receive(message);
}
}
// other unrelated methods and variables...
}
// MyComponent.java
public interface MyComponent {
public void receive(Message message);
// other unrelated methods...
}
// RendererComponent.java
public class RendererComponent implements MyComponent {
public void receive(Message message) {
if (message.getType() == Message.Type.POSITION_CHANGED) {
Point positionDifference = message.getInfo();
redraw(positionDifference);
} else if (message.getType() == Message.Type.SCORE_CHANGED) {
Integer score = message.getInfo();
redraw(score);
} // else if...
}
private void redraw(Point positionDifference) {
// draws item at new position...
}
private void redraw(Integer score) {
// draws the new score...
}
// other unrelated methods and variables..
}
I have a lot of components and they receive many different types of messages. How do I write my Message class so that I can get information of different class types from it? Do I need to change the way my component class handles messages?
The normal (and easy) way to do this kind of thing is with Java’s internal event publishing mechanisms. You define a class that represents an event, and an interface that event listeners / consumers must implement with an “event occurred” callback method. An event producer has a register method for registering an event consumer, and keeps a list of registered consumers. When the producer wants to send an event, it creates an event object and then calls the “event occurred” callback for all registered consumers.
This approach is used throughout the Java’s GUI libraries, and in other places. It is lightweight and efficient … and probably a better idea than doing this kind of thing by message passing.
A good place to start learning about events is the Introduction to Event Listeners in the Swing tutorial.