I am willing to have a design pattern choice for this common scenario:
I have a module which receives messages(MessageListener). Eeach message it receives is actually an object (MyMessage1,MyMessage2,..)
My_Message1,My_Message2 exteneds My_Message_Abstract.
Now when a message being retrieved by the the MessageListener Object(onMessage(..)) I want to do a diffident "command" depends on the message instance.. something like this:
onMessage(My_Message_Abstract msg)
{
if (msg instance of My_Message1)
{
doSomething()..
}
else if(msg instance of My_Message2)
{
doSomethingElse()..
}
}
I want to get rid of this boiler if/then code and having it better future- maintenance/dynamic/plug-ability/neat way.
So I took the Command design pattern. and I found out that I could have something like that:
in the MessageListener to have a map:
Map<Integer, MessageCommand> messageCommandsMap = new HashMap<Integer, MessageCommand>();
..
sessionTargetMap.put(MSG_1_TYPE, new Message1Command());
sessionTargetMap.put(MSG_2_TYPE, new Message2Command());
(Message1Command,Message2Command implements from Command interface)
onMessage(My_Message_Abstract msg)
{
messageCommandsMap.get(msg.getType).executeCommand(msg);
}
I didnt like the hashmap idea in the MessageListeenr in this way i am coupling all commands to that object(MessageListener).
As the solution provided at this thread: Long list of if statements in Java
Any idea how could I improve this? Mybe I should use other pattern for this idea?
thanks,