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

前端 未结 5 1149
星月不相逢
星月不相逢 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 23:05

    No matter what, you have to do some updating; the application won't just magically know which response action to do based off of the event message.

    Cases are well and good, but as the list of messages your object responds to gets longer, so does its response time. Here is a way to respond to messages that will respond at the same speed no matter how many your register with it. The example does need to use the Class object, but no other reflections are used.

    public class GameEntity {
    
    HashMap registeredEvents;
    
    public void receiveMessage(EventMessage message) {
        ActionObject action = registeredEvents.get(message.getClass());
        if (action != null) {
            action.performAction();
        }
        else {
            //Code for if the message type is not registered
        }
    }
    
    protected void registerEvent(EventMessage message, ActionObject action) {
        Class messageClass = message.getClass();
        registeredEventes.put(messageClass, action);
    }
    

    }

    public class Ship extends GameEntity {
    
    public Ship() {
        //Do these 3 lines of code for every message you want the class to register for. This example is for a ship getting hit.
        EventMessage getHitMessage = new GetHitMessage();
        ActionObject getHitAction = new GetHitAction();
        super.registerEvent(getHitMessage, getHitAction);
    }
    

    }

    There are variations of this using Class.forName(fullPathName) and passing in the pathname strings instead of the objects themselves if you want.

    Because the logic for performing an action is contained in the superclass, all you have to do to make a subclass is register what events it responds to and create an ActionObject that contains the logic for its response.

提交回复
热议问题