场景:
某些时候,会对同一个对象的多个不同属性做相同操作,代码复用原则,可以把 getter setter 用 FUNCTION 表示;
import java.util.function.BiConsumer;
import java.util.function.Function;
private static void resetAttributeByGroup(List<MSMCoreVO> datas) {
setByFunc(datas, MSMCoreVO::getBudgetPor, MSMCoreVO::setBudgetPor);
setByFunc(datas, MSMCoreVO::getActualPor, MSMCoreVO::setActualPor);
setByFunc(datas, MSMCoreVO::getBudgetOk2ship, MSMCoreVO::setBudgetOk2ship);
setByFunc(datas, MSMCoreVO::getActualOk2ship, MSMCoreVO::setActualOk2ship);
for (MSMCoreVO data : datas) {
setOk2ShipRatio(data);
setPorRatio(data);
}
}
private static void setByFunc(List<MSMCoreVO> datas, Function<MSMCoreVO, BigDecimal> getFunc, BiConsumer<MSMCoreVO, BigDecimal> setFunc) {
Optional<BigDecimal> max = datas.stream().filter(o -> Objects.nonNull(getFunc.apply(o))).map(o -> getFunc.apply(o)).max(BigDecimal::compareTo);
if (max.isPresent()) {
BigDecimal value = max.get();
for (MSMCoreVO entity : datas) {
setFunc.accept(entity, value);
}
}
}
public static void main(String[] args) {
RecipentMaintenanceEntity entity = new RecipentMaintenanceEntity();
BiConsumer<RecipentMaintenanceEntity, String> setFunc= RecipentMaintenanceEntity::setFirstName;
setFunc.accept(entity, "test ===> ");
Function<RecipentMaintenanceEntity, String> getFunc= RecipentMaintenanceEntity::getFirstName;
String firstName = getFunc.apply(entity);
System.out.println(firstName);
}