You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java游戏OOP设计:优雅存储静态方法至字段的排序方案咨询

基于函数式接口的静态方法绑定方案

1. 复用已定义的函数式接口

你在Sorting类中定义的SortingValueMethod刚好匹配所有静态排序方法的签名,完全可以用它来封装静态方法,彻底避开反射和try{}catch{}。

2. 在Block类中实现静态绑定映射

将原来的SUPPORTED_SORT_TYPES数组替换为public static final Map<SortType, Sorting.SortingValueMethod>,直接通过方法引用关联枚举值与Sorting的静态方法:

public class Block implements Sortable {
    // 静态绑定SortType到对应的排序方法
    public static final Map<SortType, Sorting.SortingValueMethod> SORT_METHOD_MAP = Map.of(
        SortType.ByPositionX, Sorting::getSortValueByPositionX,
        SortType.ByPositionY, Sorting::getSortValueByPositionY,
        SortType.ByPositionZ, Sorting::getSortValueByPositionZ,
        SortType.ByPosition2d, Sorting::getSortValueByPosition2d
    );

    @Override
    public boolean supportsSortType(SortType type) {
        // 直接通过map判断支持的排序类型,无需遍历
        return SORT_METHOD_MAP.containsKey(type);
    }

    @Override
    public double getSortValue(SortType type, double... args) throws UnsupportedSortTypeException {
        Sorting.SortingValueMethod method = SORT_METHOD_MAP.get(type);
        if (method == null) {
            throw new UnsupportedSortTypeException("Type " + type + " is unsupported for class " + Block.class.getName());
        }
        // 直接调用函数式接口实例,无反射、无异常捕获
        return method.getSortValue(this.position, args);
    }
}

3. 优化Sorting类的类型安全性(可选)

原Sorting类中的静态方法使用Object作为参数存在强制类型转换的安全隐患,可将参数类型改为Point(如果所有可排序类的位置字段都是Point类型):

public class Sorting {
    public static double getSortValueByPositionX(Point position, double... args) {
        return position.getX();
    }

    public static double getSortValueByPositionY(Point position, double... args) {
        return position.getY();
    }

    public static double getSortValueByPositionZ(Point position, double... args) {
        return position.getZ();
    }
    
    public static double getSortValueByPosition2d(Point position, double... args) {
        double width = args[0];
        return position.getX() + position.getY() * width;
    }
    
    @FunctionalInterface
    public interface SortingValueMethod {
        double getSortValue(Point field, double... args);
    }
}

修改后既消除了类型转换警告,又提升了代码安全性,同时不影响Block类中的方法引用绑定。

4. 其他可排序类的通用实现方式

对于其他实现Sortable接口的类,只需重复以下步骤即可保持代码整洁:

  • 定义自身的SORT_METHOD_MAP,绑定支持的SortType与对应的Sorting静态方法
  • 借助map实现supportsSortType和getSortValue方法,无需重复编写判断和调用逻辑

内容的提问来源于stack exchange,提问作者varikoz272

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:14:57