Java - Creating an array of methods

前端 未结 6 2061
温柔的废话
温柔的废话 2020-12-01 01:47

I\'m designing a text-based adventure game for a school progress. I have each \"level\" set up as a class, and each explorable area (node) as a method within the appropriate

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 02:05

    Whenever you think of pointer-to-function, you translate to Java by using the Adapter pattern (or a variation). It would be something like this:

    public class Node {
        ...
        public void goNorth() { ... }
        public void goSouth() { ... }
        public void goEast() { ... }
        public void goWest() { ... }
    
        interface MoveAction {
            void move();
        }
    
        private MoveAction[] moveActions = new MoveAction[] {
            new MoveAction() { public void move() { goNorth(); } },
            new MoveAction() { public void move() { goSouth(); } },
            new MoveAction() { public void move() { goEast(); } },
            new MoveAction() { public void move() { goWest(); } },
        };
    
        public void move(int index) {
            moveActions[index].move();
        }
    }
    

提交回复
热议问题