简体   繁体   中英

Saving blocks of code in variables

In Objective C you have a function blocks. You can save blocks of code in a variable and pass them as parameters.

[objects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    // Enumerating all the objects of an array
}];

In my game I have a MenuScene with MenuSceneItem s. In this case I would want to pass the code they should execute if they have been clicked. This would eliminate the need of a switch statement.

Is there a way to to is there a way to do this or something similar in Java?

In Java you can't have anonymous function blocks you need to use an anonymous class:

menuScene.executeWhenClicked(new Runnable() {
  public void run() {
    // do something
  }
});

This sounds like straightforward polymorphism eg

public interface Action {
   void doSomethingWhenPressed();
}

and just implement an object that implements the above interface. Pass that as an argument.

You'd likely do this using an anonymous class eg

// this method takes an 'Action' as an argument
passToMethod(new Action() {
   public void doSomethingWhenPressed() {
      System.out.println("Pressed!");
   }
});

In java, you create an object (it doesn't have to have an explicit class type) that extends Runnable, and put the block of code in the run method. Like so

    Runnable myDelayedBlockOfCode = new Runnable() {
        public void run() {
            doA();
            doB();
            doC();
        }
    };

If working with a framework, look closer for a framework specific interface that allows you to place such blocks of code into whatever the framework will call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM