Reputation: 47
My Java program will be receiving messages with a predefined structure. Each message has multiple fields, and the next field may have certain values (and should be processed in certain way) depending on the current field value:
For example:
1. FIELD1-FIELD2-CUSTOMDATA-OTHERDATA
2. FIELD1-FIELD2-FIELD3-CUSTOMDATA-OTHERDATA
Here, depending on the type of FIELD1, certain decoding logic should run next; So certain parser should be used.
Is there any design pattern for such ?
I have thought of defining a class for each message type and provide the input step by step to certain implementation. But this doesn't sound too good for me.
Thoughts?
Thanks in advance.
Upvotes: 2
Views: 5508
Reputation: 533590
Unless you need the structure to be changed dynamically, I would write a parser which uses a switch and listener to handle the messages.
interface MessageListener {
void message1(String field2, Object customData, Object otherData);
void message2(String field2, String field3, Object customData, Object otherData);
// other message types
}
MessageListener ml =
String firstField = getField();
switch(firstField) {
case messageType1: {
String field2 = getField();
Object customData = getData();
Object otherData = getData();
ml.message1(field2, customData, otherData);
break;
}
case messageType2: {
String field2 = getField();
String field3 = getField();
Object customData = getData();
Object otherData = getData();
ml.message2(field2, field3, customData, otherData);
break;
}
//parse other message types
default:
// report unknown message type.
}
Upvotes: 1
Reputation: 691845
This looks like a good candidate for the State pattern to me.
Your parser would have an initial state (implementation of an abstract class or interface), and ask this state to handle the next token.
Depending on the value of the token the state modifies the context, and returns the appropriate next State instance. And you repeat this until the state throws an exception because the next token is not expected, or until the last token has been handled and the last state doesn't expect another token. At the end, either the parsing failed, or it succeeded and the context contains the parsed data.
public interface State {
State nextState(Context context, String token) throws UnexpectedTokenException;
boolean isFinal();
}
Upvotes: 0
Reputation: 37506
Your best bet would be to define a few enumerations with the range of actions for each field and then create a generic message class. A utility class that handles things like verifying that you are using valid combinations would also be good.
Don't overthink it. Take the most straight-forward path instead of relying on a lot of abstractions that you probably won't need.
One of the advantages of this approach is that with JAX-RS and JAX-WS you can annotate your message class in such a way that the APIs will automagically convert it into XML (maybe JSON too?) if you need to expose your message passing to external systems.
Upvotes: 1