java8 Function 应用场景 –代码重构
旧代码:
import org.springframework.beans.BeanUtils;
import java.util.function.Function;
public class J8FunctionDemo1Test {
public static void main(String[] args) {
CarVO byCompany = getCarByCompany("长城");
CarVO carByName = getCarByName("长安CS75");
}
/**
* 旧代码
*/
public static CarVO creteByName(String name){
Car car= new Car().setName(name).setCompany("长安");
CarVO vo=new CarVO();
BeanUtils.copyProperties(car,vo);
vo.setAddress("重庆");
vo.setStatus(0);
return vo;
}
/**
* 旧代码
*/
public static CarVO createByCompany(String company){
Car car= new Car().setName("长城H6").setCompany(company);
car.setStatus(0);
CarVO vo=new CarVO();
BeanUtils.copyProperties(car,vo);
vo.setAddress("北京");
vo.setStatus(0);
return vo;
}
}
使用Function 函数重构代码:
import org.springframework.beans.BeanUtils;
import java.util.function.Function;
public class J8FunctionDemo1Test {
public static void main(String[] args) {
Car byCompany = getCarByCompanyFn("长城");
Car carByName = getCarByNameFn("长安CS75");
}
/**
* 新function代码
*/
public static CarVO createByFunction(String param,Function<String,CarVO> function){
Car car= function.apply(param);
CarVO vo=new CarVO();
BeanUtils.copyProperties(car,vo);
vo.setAddress("北京");
vo.setStatus(0);
return vo;
}
/**
* 新function代码
*/
public static CarVO getCarByNameFn(String name){
return createByFunction(name,arg->creteByName(name));
}
/**
* 新function代码
*/
public static CarVO getCarByCompanyFn(String company){
return createByFunction(company,arg->createByCompany(company));
}
}
可以看到使用function代码更简约
原创文章,作者:sunnyman218,如若转载,请注明出处:https://blog.ytso.com/243562.html