문제

ex:

public class Game{ 
  String level;

  public void update(){
    update+"level"(); //calls diff. method depending on variable
  }

  public static void setLevel(String lv){
  level = lv;
  }

  private updateLevelOne(){
  .....
  }

  private updateLevelTwo(){
  .....
  }      
}

public class Level{......
      Game.setLevel(One);
}

I know the top statement wont work. But I was wondering if its possible to make a call in such way that I wouldn't have to use a if/switch statement and go directly to the method.

도움이 되었습니까?

해결책

Either use a switch statement or objects:

Switch statement:

public class Game {

    private int level;

    public void update() {
        switch(level) {
            case 1:
                updateLevelOne();
                break;
            case 2:
                updateLevelTwo();
                break;
        }
    }

    public static void setLevel(int lv) {
        level = lv;
    }

    private updateLevelOne() {
        .....
    }

    private updateLevelTwo() {
        .....
    }
}

Alternatively, make your levels objects:

public class Game {

    private Level[] levels;
    private int currentLevel;

    public Game() {
        levels = new Level[2]
        levels[0] = new Level();
        levels[1] = new Level();
        currentLevel = 0;
    }

    public void update() {
        levels[currentLevel].update();
    }

    public static void setLevel(int newLevel) {
        currentLevel = newLevel;
    }
}

public class Level {

    public Level() {

    }

    public void update() {

    }
}

Objects are preferred but you can go either way. You could also go with the reflection package, but that's a worse idea that will be harder to understand.

다른 팁

No, it's not possible to create method names dynamically like this.

You should look up the Strategy pattern. This means you set some Level interface as a field in your class. All your different levels should implement this interface, and each should implement some update method. At runtime, you can set this field with the exact implementation that you need at that time and you can call update() on it. This will delegate to the required implementation.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top