【问题标题】:Passing a function as a parameter onto a list of objects将函数作为参数传递到对象列表中
【发布时间】:2016-04-08 02:24:11
【问题描述】:

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

这里是一些示例 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
}

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

【问题讨论】:

  • 你能显示你的对象列表的定义吗?应该有更好的方法来做到这一点

标签: java function lambda


【解决方案1】:

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

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

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),自己创建。这可以像这样使用 f.e.查找是否有任何门打开:

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

【讨论】:

    猜你喜欢
    • 2018-02-23
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2023-03-04
    • 1970-01-01
    • 2018-04-17
    相关资源
    最近更新 更多