Java - 消息处理器设计模式
我的 Java 程序将接收具有预定义结构的消息。每个消息有多个字段,并且下一个字段可能具有特定值(并且应该以特定方式处理),具体取决于当前字段值:
For example:
1. FIELD1-FIELD2-CUSTOMDATA-OTHERDATA
2. FIELD1-FIELD2-FIELD3-CUSTOMDATA-OTHERDATA
这里,根据FIELD1的类型,接下来应该运行特定的解码逻辑;所以应该使用特定的解析器。
有这样的设计模式吗?
我想过为每种消息类型定义一个类,并逐步向某些实现提供输入。但这对我来说听起来不太好。
想法?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
责任链或策略 ?
Chain of Responsibilities or Strategy ?
除非您需要动态更改结构,否则我会编写一个解析器,它使用开关和侦听器来处理消息。
Unless you need the structure to be changed dynamically, I would write a parser which uses a switch and listener to handle the messages.
最好的选择是定义一些枚举以及每个字段的操作范围,然后创建一个通用消息类。处理诸如验证您是否使用有效组合之类的实用程序类也很好。
别想太多。采用最直接的路径,而不是依赖大量您可能不需要的抽象。
这种方法的优点之一是,使用 JAX-RS 和 JAX-WS,如果您需要公开消息传递,您可以以 API 会自动将其转换为 XML(也可能是 JSON?)的方式注释您的消息类到外部系统。
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.
对我来说,这看起来是状态模式的一个很好的候选者。
您的解析器将有一个初始状态(抽象类或接口的实现),并要求该状态处理下一个标记。
根据令牌的值,状态会修改上下文,并返回适当的下一个 State 实例。重复此操作,直到状态因不需要下一个令牌而引发异常,或者直到处理了最后一个令牌并且最后一个状态不需要另一个令牌。最后,要么解析失败,要么解析成功并且上下文包含解析的数据。
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.