将函数作为参数传递到对象列表

问题描述 投票:1回答:1

因此,我正在尝试基于标签的概念创建一个基本的游戏引擎,其中每个对象都有一堆标签,我可以用它来分组像墙段这样的东西并一次对它们执行操作。因为我不想用循环来围绕每个函数来在每个对象上调用它,所以我试图创建一个可以在每个对象上调用传递方法的方法。

这是一些示例suto-code:

//have a list of objs. some door, some not.

//an example of stuff I could want to do
//  - check returns on any functions called
//  - call a function on a bunch of objects, possibly with parameters
if (runOnTag("door", isClosed())[aPositionInReturnList] == true){
    runOnTag("door", open());
}

//the method
public couldBeAnyType[] runOnTag(String tag, function(anyPerams)){    //dont want the function to compile here
    for (String currentObj : listOfObjsWith[tag]){
        returns[index++] = currentObj.function(anyPerams);     //so that it can be executed on this object
    }
    return returns;    //want to be able to colect returns
}

我已经查看了这类问题的一些其他答案,但我不明白它们中发生了什么。如果有人能够更简单地解释它,我会非常感激。

java function lambda
1个回答
0
投票

假设:您没有动态更改标签的对象。

为什么不将标签实现为接口?这比字符串匹配更快,类型安全且通常更有效。

interface Door {boolean isClosed(); void open();}

class State {
   private Collection<Object> gameObjects;

   public <T,R> Stream<R> onTagged(Class<T> type, Function<T,R> apply) {
      return gameObjects
           .stream()
           .filter(type::isInstance)
           .map(type::cast)
           .map(apply);
   }
}

忽略名称(onTagged),制作自己的名字。这可以像这样使用。找到是否有任何门打开:

State state = ...;
if(state.onTagged(Door.class, door -> !door.isClosed()).anyMatch(Boolean.TRUE::equals)) {
  // ... do stuff ...
}

然而,你会发现它通常更好,因为这样你就可以很容易地编写操作(map / filter / any *):

   public <T> Stream<T> withTag(Class<T> type) {
      return gameObjects
           .stream()
           .filter(type::isInstance)
           .map(type::cast);
   }

if(state.withTag(Door.class).anyMatch(door -> !door.isClosed())) {
  // ... do stuff ...
}
© www.soinside.com 2019 - 2024. All rights reserved.