MessageReceivedListener

MessageReceivedListener

因此,我在stackoverflow上看到了多个问题,询问如何在Java中实现事件,但似乎没有一个问题提供了其他示例,然后“阅读此内容”。

有人可以请客提供一个简洁的示例,说明如何实现以下C#代码的基本等效代码吗?

public event EventHandler<MessageReceivedEventArgs> MessageReceived;
protected virtual void OnMessageReceived(Socket socket, CommandType commandType, MemoryStream message)
{
    if (this.MessageReceived != null)
    {
        this.MessageReceived(this, new MessageReceivedEventArgs(socket, commandType, message));
    }
}

最佳答案

通常,Java中不使用多播委托。如果您不需要多播,那么代码将如下所示:

public interface MessageReceivedListener {
    void onMessageReceived(Object sender, MessageReceivedEventArgs e);
}

private MessageReceivedListener messageReceivedListener;

public void setMessageReceivedListener(MessageReceivedListener listener) {
    this.messageReceivedListener = listener;
}

protected void onMessageReceived(Socket socket, CommandType commandType, MemoryStream message) {
    if (this.messageReceivedListener != null) {
        this.messageReceivedListener.onMessageReceived(this,
           new MessageReceivedEventArgs(socket, commandType, message));
    }
}


如果要实现多播,则可以创建带有侦听器的容器,并遍历这些侦听器和调用处理程序。在这种情况下,将存在用于管理活动侦听器的addMessageReceivedListenerremoveMessageReceivedListener方法。

10-08 13:28