[英]Netty.io messageReceived override without instanceof
In netty, MessageEvent (wrapper for messages) has a method Object getMessage() to get the real carried message from the network. 在Netty中,MessageEvent(消息包装器)具有对象Object getMessage()的方法,可从网络获取实际携带的消息。 Reading the source I noticed they heavily use the instanceof operator to switch among methods.
阅读源代码后,我注意到他们大量使用instanceof运算符在方法之间进行切换。
However, having a wide variety of message types I would like to avoid a method like this: 但是,由于具有多种消息类型,我希望避免使用以下方法:
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
if (e.getMessage() instanceof MessageType1) {
...
} else if (e.getMessage() instanceof MessageType2) {
...
} ... {
...
} else if (e.getMessage() instanceof MessageTypeN) {
...
} else {
ctx.sendUpstream(e);
}
}
Writing different methods taking advantage of polymorphism would be much better, like: 利用多态性编写不同的方法会更好,例如:
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
// MessageType implements Message
if (e.getMessage() instanceof Message) {
handleMessage(ctx, (Message) e.getMessage());
} else {
ctx.sendUpstream(e);
}
}
void handleMessage(ChannelHandlerContext ctx, MessageType1 m) {
...
}
...
void handleMessage(ChannelHandlerContext ctx, MessageTypeN m) {
...
}
But i cannot due to downcasting limitations. 但是我不能由于垂头丧气的限制。 Is there a clean way to do this or am I tied to instanceof cascade?
有没有一种干净的方法可以执行此操作,或者我是否绑定到instanceof级联? I could bring the logic out the Handler using .doSomething() methods inside Message sub-types but I'd like to keep the business logic inside the netty pipeline.
我可以在Message子类型内使用.doSomething()方法将逻辑带出处理程序,但我想将业务逻辑保留在netty管道内。
Solved applying Visitor Pattern: 解决了应用访问者模式:
public interface Handler {
void handleMessage(ChannelHandlerContext ctx, MessageType1 m);
void handleMessage(ChannelHandlerContext ctx, MessageType2 m);
...
void handleMessage(ChannelHandlerContext ctx, MessageTypeN m);
}
then: 然后:
@Sharable
public class MessageHandler extends SimpleChannelHandler implements Handler {
...
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
if (e.getMessage() instanceof Message) {
Message m = (Message) e.getMessage();
m.handleTo(ctx, this);
} else {
ctx.sendUpstream(e);
}
}
@Override
public void handleMessage(ChannelHandlerContext ctx, MessageType1 m) {
...
}
and 和
public interface Message {
/*
* Will be {
* handler.handleMessage(ctx, this);
* }
* everywhere.
*/
void handleTo(ChannelHandlerContext ctx, Handler handler);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.