简体   繁体   中英

Akka actor implementation: extension or injection?

I am brand new to Akka (I'm using the Java lib v2.3.9), and am wondering what the tradeoff(s) is between two competing actor implementation strategies. On one hand I could implement my actors the standard way:

// Groovy pseudo-code
class StormTrooper extends UntypedActor {
    @Override
    void onReceive(Object message) {
        if(message instanceof ExecuteOrder66) {
            // Betray all Jedi, serve the Emperor!
        }
    }
}

class DarthVader extends UntypedActor {
    @Override
    void onReceive(Object message) {
        if(message instanceof Feels) {
            // Betray the Emperor, save your son!
        }
    }
}

class Emperor extends UntypedActor {
    @Override
    void onReceive(Object message) {
        if(message instanceof Mace) {
            // Transform into your true self!
        }
    }
}

...instead of doing that, I could add a layer of abstraction via injection:

class StarWarsCharacter extends UntypedActor {
    @Inject // Injected behavior; implementation doesn't matter
    BehaviorHandler behaviorHadler

    @Override
    void onReceive(Object message) {
        behaviorHandler.handle(message)
    }
}

interface BehaviorHandler {
    void handle(Object message)
}

class StormTrooperBehaviorHandler implements BehaviorHandler {
    @Override
    void handle(Object message) {
        // Betray all Jedi, serve the Emperor!
    }
}

class DarthVaderBehaviorHandler implements BehaviorHandler {
    @Override
    void handle(Object message) {
        // Betray the Emperor, save your son!
    }
}

class EmperorBehaviorHandler implements BehaviorHandler {
    @Override
    void handle(Object message) {
        // Transform into your true self!!
    }
}

Are there performance/classloading benefits to only having one type of actor and injecting it with different BehavioHandler implementations? Is there a reason why I would not want to do this and use the "standard" actor implementation?

If you just want to use your Actor as a way of dispatching messages to handlers, then the 2nd (non standard) way will be fine, and could give you some benefits in terms of code structure - eg the fact that BehaviorHandler is a single method interface would allow you to implement it with a lambda.

However , Actors are not simply method dispatchers. They provide a variety of methods that you will need as your system grows in complexity.

See http://doc.akka.io/docs/akka/2.0/java/untyped-actors.html#untypedactor-api

A typical, moderate sized Akka system will need references to self , sender and context which are defined on UntypedActor .

In short: if you don't use inheritance then you are giving up more than you realise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM