Im trying to come up with a solution where the class that processes a "message" is selected at runtime depending on the message type. I know that i can use something like this
if msg_type = "A"
MsgAProcessor.execute(message);
else if msg_type = "B"
MsgBProcessoror = execute(message);
....
....
....
I dont want to use the above approach as i dont want the code to know anything about the message types that i could be processing. I want to be able to in the future add a new message processor for a new message type. The solution i am thinking of at the moment is as follows
There are 3 message processors at the moment
MsgAProcessor
MsgBProcessor
MsgBProcessor
All three classes have a method called execute which will process the message in its own way. I have created an interface called MsgProcessor and added the execute() method in the interface.
Now i am having difficulty in knowing which message processor the caller should call without having to check the message type. For example, i cant do this
MsgProcessor proc = new MsgAprocessor() proc.execute()
The above will stil be required to be in an if statement as it needs to be called just after finding out the message type. I would also like to avoid instantiating using the implementation class type.
Is there a better way of achieving the same?
I want to be able to just call MsgProcessor.execute from the interface and have the runtime environment know which implementation class to call based on the message type.
This is a simple command pattern.