I have written an implementation of the observer pattern that allows messages to be passed to listeners in what would normally be the notify() method. For example a subscriber sub-class might look like the pseudo-code below, where Message is a simple class that can be sub-classed and made to contain value objects or other data.
class MySubscriber extends Subscriber
{
@Override
public void notify( Message m )
{
if( m.getClass == MyMessage )
{
MyMessage myMessage = ( MyMessage ) m;
if( myMessage.name == MyMessage.START )
{
// -- Finally do something here
}
}
if( m.getClass == MyOtherMessage )
{
MyOtherMessage myOtherMessage = ( MyOtherMessage ) m;
if( myOtherMessage.name == MyOtherMessage.INIT_SOMETHING )
{
// -- Finally do something else here
}
}
}
}
Using conditionals like this to determine the message type seems a bit redundant and can get tedious in cases where a subscriber is listening for many message types. However, it is pretty explicit, easy to read and the implementation is quite simple. Is there a cleaner approach to achieve a similar result?
Btw, I attempted to add the tags: "observer" and "introspection" to this question but apparently I don't have enough points on this Stack Exchange site.