又一个Java事件问题

时间:2011-05-02 06:05:53

标签: java android events design-patterns

所以我在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));
    }
}

1 个答案:

答案 0 :(得分:1)

通常在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方法来管理活动侦听器。