检查消息类型时避免使用instanceof [英] Avoiding instanceof when checking a message type

查看:187
本文介绍了检查消息类型时避免使用instanceof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:客户端类根据它接收的消息类型执行不同的行为。我想知道是否有更好的方法这样做,因为我不喜欢instanceof和if语句。

I have the following situation where a client class executes different behavior based on the type of message it receives. I'm wondering if there is a better way of doing this since I don't like the instanceof and the if statements.

我想做的一件事就是拉动客户端类之外的方法并将它们放入消息中。我会在IMessage接口中放入一个类似process()的方法,然后将消息特定的行为放在每个具体的消息类型中。这会使客户端变得简单,因为它只调用message.process()而不是检查类型。但是,唯一的问题是条件中包含的行为与对Client类中包含的数据的操作有关。因此,如果我在具体的消息类中实现了一个进程方法,我将不得不将它传递给客户端,我不知道这是否真的有意义。

One thing I thought of doing was pulling the methods out of the client class and putting them into the messages. I would put a method like process() in the IMessage interface and then put the message specific behavior in each of the concrete message types. This would make the client simple because it would just call message.process() rather than checking types. However, the only problem with this is that the behavior contained in the conditionals has to do with operations on data contained within the Client class. Thus, if I did implement a process method in the concrete message classes I would have to pass it the client and I don't know if this really makes sense either.

public class Client {
    messageReceived(IMessage message) {
        if(message instanceof concreteMessageA) {
            concreteMessageA msg = (concreteMessageA)message;
            //do concreteMessageA operations
        }
    }
        if (message instanceof concreteMessageB) {
            concreteMessageb msg = (concreteMessageB)message;
            //do concreteMessageB operations
        }
}


推荐答案

避免实例测试的简单方法是多态分派;例如

The simple way to avoid instanceof testing is to dispatch polymorphicly; e.g.

public class Client {
    void messageReceived(IMessage message) {
        message.doOperations(this);
    }
}

其中每个消息类定义一个合适的 doOperations(客户端客户端)方法。

where each message class defines an appropriate doOperations(Client client) method.

编辑:第二种解决方案,更符合要求。

second solution which better matches the requirements.

用switch语句替换'instanceof'测试序列的替代方法是:

An alternative that replaces a sequence of 'instanceof' tests with a switch statement is:

public class Client {
    void messageReceived(IMessage message) {
        switch (message.getMessageType()) {
        case TYPE_A:
           // process type A
           break;
        case TYPE_B:
           ...
        }
    }
}

每个IMessage类都需要定义一个 int getMessageType()方法来返回相应的代码。 Enum的工作方式也很好,IMO更优雅。

Each IMessage class needs to define an int getMessageType() method to return the appropriate code. Enums work just as well ints, and are more more elegant, IMO.

这篇关于检查消息类型时避免使用instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆