构造函数当做Function用做方法入参

SpecialSpeculator / 2024-08-23 / 原文

1.先有一个类,有一个构造函数

public abstract class AbstractMonitorAction<T> implements Action<T>{
}

public class StopMonitorAction extends AbstractMonitorAction<CheckResult> {
        private final List<ScanResult> scanResults;
        private List<CheckResult> checkResults;

        public StopMonitorAction(List<ScanResult> scanResults) {
            this.scanResults = scanResults;
        }

        @Override
        public void execute() {
            checkResults = Lists.newArrayList();
            List<List<ScanResult>> partitions = Lists.partition(scanResults, 500);

            for (List<ScanResult> partition : partitions) {
                processPartition(partition);
            }
        }
}

2.定义一个Function用来指定不同的构造函数

Function<List<ScanResult>,Action<CheckResult>>

入参:List
出参:Action 接口

3.分析上述构造函数

  1. 发现构造函数的入参就是List
  2. 构造函数一般返回类自己对象,因为类有继承关系,父类有实现接口逻辑,用多态特性可以用接口接受返回类型
  3. 所有构造函数是可以用做Function类型的接收的

4.实际定义例子

private void processScanResults(List<ScanResult> scanResults, String actionName, List<CheckResult> checkResults, Function<List<ScanResult>, Action<CheckResult>> actionConstructor) {
        List<ScanResult> filteredResults = scanResults.stream()
                .filter(scanResult -> scanResult.getScanValue().equalsIgnoreCase(actionName))
                .collect(Collectors.toList());

        if (!filteredResults.isEmpty()) {
            Action<CheckResult> action = actionConstructor.apply(filteredResults);
            action.execute();
            checkResults.addAll(action.getResult());
        }
    }
# 使用,其中StopMonitorAction::new 会自动识别为是Function<List<ScanResult>, Action<CheckResult>> 类型
processScanResults(scanResults, TaiShanMonitorScanExector.MonitorAction.STOP_MONITOR.name(), checkResults, StopMonitorAction::new);