java - 将函数作为参数传递给对象列表

标签 java function lambda

因此,我正在尝试基于标签的想法制作一个基本的游戏引擎,其中每个对象都有一堆标签,我可以使用它们对墙段等内容进行分组并同时对它们执行操作。由于我不想用循环包围每个函数来在每个对象上调用它,因此我尝试创建一个可以在每个对象上调用传递的方法的方法。

这是一些示例 suto 代码:

//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
}

我已经浏览了此类问题的许多其他答案,但我不明白其中发生了什么。如果有人能更简单地解释它,我将不胜感激。

最佳答案

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

为什么不将标签实现为接口(interface)?这比字符串匹配更快、类型安全并且通常更高效。

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 ...
}

关于java - 将函数作为参数传递给对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36490464/

相关文章:

java - MySQL 查询结果很慢

algorithm - 实现求根功能

ruby - 测试 lambda

c# - C# 中的 lambda 表达式和消息框

c++ - Visual Studio 中的嵌套 lambda

java - 开源 OCR

java - Android服务定期在后台执行任务?

java - 使用 Hibernate 存储统计信息

c - K&R函数声明

bash - 添加到 $PATH 之前