函数式接口 + Lambda实现函数指针

坏味道:

Long count = 0L;
List list = new ArrayList<>();

if (type == 0) {
    count = dao.pageCountA(query);
    if (count == 0) {
        return;
    }
    list = dao.pageQueryA(query);
    
} else {
    count = dao.pageCountB(query);
    if (count == 0) {
        return;
    }
    list = dao.pageQueryB(query);
}

坏味道:相同的代码多次出现

函数式接口 + Lambda实现类似功能:

函数式接口定义:

@FunctionalInterface
public interface PageCountHelper {
    Long pageCount(Query query);
}

@FunctionalInterface
public interface PageQueryHelper {
    List pageQuery(Query query);
}

配合Lambda使用:

PageCountHelper pageCountHelper = (Query query) -> dao.pageCountA(query);
PageQueryHelper pageQueryHelper = (Query query) -> dao.pageQueryA(query);

if (type != 0) {
    pageCountHelper = (Query query) -> dao.pageCountB(query);
    pageQueryHelper = (Query query) -> dao.pageQueryB(query);
}

Long count = pageCountHelper.pageCount(query);
if (count == 0) {
    return;
}
List result = pageQueryHelper.pageQuery(query);
参考资料:

1、函数式接口@FunctionalInterface

你可能感兴趣的:(函数式接口 + Lambda实现函数指针)