如何减少ReceiveActor的代码重复

本文关键字:代码 何减少 ReceiveActor | 更新日期: 2023-09-27 18:17:20

我有可切换行为的接收Actor,通过成为()方法切换。为了监视子演员,我必须添加Receive<终止>调用每个状态方法。

例如,我必须将其粘贴到Ready, Working1和Working2方法中

public class SomeActor : ReceiveActor
{
    public SomeActor()
    {
        // create child actors
        Become(Ready);
    }
    private void Ready()
    {
        Receive<InitMessage>(m =>
        {
            Become(Working1);
        });
        Receive<Terminated>(m =>
        {
            // duplicated termination stuff 
            Become(Terminated);
        });
    }
    private void Working1()
    {
        Receive<InitMessage>(m =>
        {
            Become(Working2);
        });
        Receive<Terminated>(m =>
        {
            // duplicated termination stuff 
            Become(Terminated);
        });
    }
    private void Working2()
    {
        Receive<InitParcerMessage>(m =>
        {
            Become(Working1);
        });
        Receive<Terminated>(m =>
        {
            // duplicated termination stuff 
            Become(Terminated);
        });
    }
    private void Terminated()
    {
        // do some stuff
    }
}

如何减少ReceiveActor的代码重复

您正在使用lambda来执行操作,相反,您可以创建一个私有方法,该方法以Terminated类型作为参数,并在Receive操作中使用MethodGroup

public class SomeActor : ReceiveActor
{
    public SomeActor()
    {
        // create child actors
        Become(Ready);
    }
    private void Ready()
    {
        Receive<InitMessage>(m =>
        {
            Become(Working1);
        });
        ConfigureReceive();
    }
    private void Working1()
    {
        Receive<InitMessage>(m =>
        {
            Become(Working2);
        });
        ConfigureReceive();
    }
    private void Working2()
    {
        Receive<InitParcerMessage>(m =>
        {
            Become(Working1);
        });
        ConfigureReceive();
    }
    private void Terminated()
    {
        // do some stuff
    }
    private void ConfigureReceive()
    {
        // Register Receive actors here
        Receive<Terminated>(p => HandleTermination(p));
    }
    // Here's our method to perform the same job with our Terminated parameter
    private void HandleTermination(Terminated termination)
    {
        // Call our Become method
        Become(Terminated);
    }
}