I'm using PubNub in Java and you essentially sub-class from SubscribeCallback
to implement receiving a message. It looks like this:
public abstract class SubscribeCallback {
public abstract void status(PubNub pubnub, PNStatus status);
public abstract void message(PubNub pubnub, PNMessageResult message);
public abstract void presence(PubNub pubnub, PNPresenceEventResult presence);
}
My messages are all of different classes with different payloads all inheriting from a Message
class, so, my message
method looks something like this:
@Override
final public void message(PubNub pubnub, PNMessageResult messageResult) {
Message message = getMessage(messageResult);
if (message instanceof DisplayerChanged) {
message((DisplayerChanged) message);
} else if (message instanceof DisplayersChanged) {
message((DisplayersChanged) message);
} else if (message instanceof NewScreenshotsToRender) {
message((NewScreenshotsToRender) message);
} else if (message instanceof RendererChanged) {
message((RendererChanged) message);
} else if (message instanceof RenderersChanged) {
message((RenderersChanged) message);
} else if (message instanceof ScreenshotRendered) {
message((ScreenshotRendered) message);
} else if (message instanceof SitesChanged) {
message((SitesChanged) message);
} else if (message instanceof UsersChanged) {
message((UsersChanged) message);
} else {
throw new RuntimeException("Received unexpected message type: " + messageResult);
}
}
This looks horrible. Is there a better way of doing this dispatch?
The reason why I'm calling another method called message
is so that different apps can inherit from this class and override message
for the particular class of message it wants to handle.