等价于Java中的C#Action()委托?

时间:2019-05-02 08:23:38

标签: java c#

C#引入了委托的概念,代表了无需知道目标对象即可调用的方法。 在C#API中,我有一个代码:

var onReadyAction = new Action(() => OnServerStateChangedSubject.OnNext(ServerState.Connected));
var onTerminatedAction = new Action(() => OnServerStateChangedSubject.OnNext(ServerState.Disconnected));

其中OnServerStateChangedSubject.OnNext(ServerState.Connected));是动作,表明服务器状态。 问题:如何在Java中实现? 方法代码:

protected TradingClientWithQueue //Client class// KeepConnectAlive()
{
    var onReadyAction = new Action(() => OnServerStateChangedSubject.OnNext(ServerState.Connected));
    var onTerminatedAction = new Action(() => OnServerStateChangedSubject.OnNext(ServerState.Disconnected));

    if (Client == null)
    {
        Client = new TradingClientWithQueue();
        //events 
        Client.OnPacketReceived.Subscribe(OnDataPacketReceivedSubject.OnNext);
        ClientSubscribeOnTerminated(onTerminatedAction);

        Client.OnClientException.Subscribe(OnClientExceptionSubject.OnNext);
        Client.OnClientReady.Subscribe(isReady =>
        {
            AuthenticateClient();
            onReadyAction();
        });

        Client.Connect(Host, Port);
    }
    else
    {
        ClientSubscribeOnTerminated(onTerminatedAction);
        Client.Reconnect(Host, Port);
    }

    return Client;
}

1 个答案:

答案 0 :(得分:0)

等效于委托是一个功能接口。

Action是一个消耗项目并返回void的函数。等效功能接口的最明显示例是Consumer<T>