I looked at the answers for this question: Design pattern for handling multiple message types
and I'm in a similar boat. The difference I have is, I'm using an existing protobuf schema that I cannot change. The protobuf schema does have the messageType property. The generated code looks like
TradeMessage.parseFrom(byte[] bytes)
OtherMessage.parseFrom(byte[] bytes)
AnotherMessage.parseFrom(byte[] bytes)
So right now I have a factory pattern that when a message comes in in the receiver
MessageReceiver.java
Object parser = messageParserFactory.getParser(messageType);
Get the type of parser
MessageParserFactory.java
public MessageParser getParser(int messageType) {
if (messageType = Constants.TRADE_MESSAGE) {
return new TradeParser();
} else if (messageType = Constants.OTHER_MESSAGE) {
return new OtherParser();
}
return null;
}
Basically repeated work for all the different message types that essentially just wrap the generated parseFrom method.
public interface MessageParser {
void doParse(byte[] bytes);
}
TradeParser.java
public void doParse(byte[] bytes) {
TradeParser.parseFrom(bytes);
}
OtherParser.java
public void doParse(byte[] bytes) {
OtherParser.parseFrom(bytes);
}
AnotherParser.java
public void doParse(byte[] bytes) {
AnotherParser.parseFrom(bytes);
}
It works but is there a better way since basically all the parsers I create for each message type do the exact same thing and just call parseFrom
.