Java - Creating an array of methods

前端 未结 6 2066
温柔的废话
温柔的废话 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:19

    Since Java does not have the concept of methods as first-class entities, this is only possible using reflection, which is painful and error-prone.

    The best approximation would probably be to have the levels as enums with a per-instance implementation of a method:

    public enum Level1 implements Explorable{
        ROOM1 {
            public void explore() {
                // fight monster
            }
        }, ROOM2 {
            public void explore() {
                // solve riddle
            }
        }, ROOM3 {
            public void explore() {
                // rescue maiden
            }
        };
    
    }
    
    public interface Explorable{
        public abstract void explore();    
    }
    
    public static void move(Explorable[] adjacentNodes, int index)
    {
        adjacentNodes[index].explore();
    }
    

    However, this is a bit of an abuse of the enum concept. I wouldn't use it for a serious project.

提交回复
热议问题