How to call the correct method in Scala/Java based the types of two objects without using a switch statement?

前端 未结 5 1164
星月不相逢
星月不相逢 2020-12-28 22:28

I am currently developing a game in Scala where I have a number of entities (e.g. GunBattery, Squadron, EnemyShip, EnemyFighter) that all inherit from a GameEntity class. Ga

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 22:47

    I'd be tempted to elevate every message type into a method signature and Interface. How this translates into Scala I'm not totally sure, but this is the Java approach I would take.

    Killable, KillListener, Breachable, Breachlistener and so on will surface the logic of your objects and commonalities between them in a way which permits runtime inspection (instanceof) as well as helping with runtime performance. Things which don't process Kill events won't be put in a java.util.List to be notified. You can then avoid the creation of multiple new concrete objects all the time (your EventMessages) as well as lots of switching code.

    public interface KillListener{
        void notifyKill(Entity entity);
    }
    

    After all, a method in java is otherwise understood as a message - just use raw java syntax.

提交回复
热议问题