我编写了一些使用过滤器设计模式的代码,如下所示:

public class SingleLengthCriteria implements XsamCriteria {

private final FilterLength filterLength;

public SingleLengthCriteria(FilterLength filterLength)  {
  this.filterLength = filterLength;
}

@Override
public List<XsamRecord> meetRecordCriteria(List<XsamRecord> records) {
  List<XsamRecord> spanLengthRecords = new ArrayList<>();

  for(XsamRecord record : records){
    if(record.getXs() >= filterLength.getMin() && record.getXs() <= filterLength.getMax()){
    spanLengthRecords.add(record);
    }
  }

  return spanLengthRecords;
}


FilterLength只是具有最小和最大坐标的pojo。

XsamRecord是要过滤的对象。在此示例中,我过滤了XsamRecords getXs方法,该方法简单地返回整数。

这一切都很好,但是我也希望为其他getx...方法创建相同的东西(它们也返回整数)。例如,我有getxLgetxR。一遍又一遍地为不同的吸气剂写同样的东西并不能使事情保持干燥。

有什么方法可以将get..方法传递到构造函数中,以便它知道在下面的for循环中调用哪个方法?

提前致谢!

最佳答案

是的,有一种方法可以使用方法引用。语法为例如XsamRecord::getXs

关联参数的类型为Function<XsamRecord, Integer>

public class SingleLengthCriteria implements XsamCriteria {

private final FilterLength filterLength;
private final Function<XsamRecord, Interger> propertyValueGetter;

public SingleLengthCriteria(FilterLength filterLength, Function<XsamRecord, Interger> propertyValueGetter)  {
  this.filterLength = filterLength;
  this.propertyValueGetter = propertyValueGetter;
}

@Override
public List<XsamRecord> meetRecordCriteria(List<XsamRecord> records) {
  List<XsamRecord> spanLengthRecords = new ArrayList<>();

  for(XsamRecord record : records){
    final Integer value = propertyValueGetter.apply(record);
    if(value >= filterLength.getMin() && value <= filterLength.getMax()){
    spanLengthRecords.add(record);
    }
  }

  return spanLengthRecords;
}


用作:

new SingleLengthCriteria(..., XsamRecord::getXs);
new SingleLengthCriteria(..., XsamRecord::getOtherProperty);

10-05 19:02