如何简化并泛化Java检查条件的代码实现?
简化Java多条件检查实现方案
核心思路
利用Java 8+的Lambda表达式和函数式接口,把分散的检查逻辑封装到工具类里,直接通过Lambda或方法引用组合条件,彻底告别一个个的Model类,同时避免重复传参。
步骤1:定义通用函数式接口
先写一个函数式接口,统一描述对Teste对象的检查逻辑:
@FunctionalInterface public interface ConditionChecker { boolean check(Teste teste); }
步骤2:封装检查逻辑到工具类
把所有isBlue、isSad这类检查方法集中到一个工具类,方法直接接收Teste对象,不用每次传字符串:
public class TesteConditions { // 检查是否为蓝色 public static boolean isBlue(Teste teste) { return "blue".equals(teste.getColor()); } // 检查是否处于悲伤状态 public static boolean isSad(Teste teste) { return "sad".equals(teste.getMood()); } // 可扩展其他检查方法,比如isRed、isHappy等 }
步骤3:直接组合条件使用
现在不需要再写Model1、Model2这类类了,直接用Lambda或者方法引用快速组合条件:
// 单个条件检查 ConditionChecker onlyBlue = TesteConditions::isBlue; // 组合条件:蓝色 或 悲伤 ConditionChecker blueOrSad = teste -> TesteConditions.isBlue(teste) || TesteConditions.isSad(teste); // 组合条件:蓝色 且 不悲伤 ConditionChecker blueAndNotSad = teste -> TesteConditions.isBlue(teste) && !TesteConditions.isSad(teste); // 调用示例 Teste sample = new Teste("blue", "happy"); boolean isMatch = blueOrSad.check(sample); // 返回true
进阶优化:链式组合条件(可选)
如果想让条件组合更优雅,可以给ConditionChecker接口加几个默认方法,支持链式调用:
@FunctionalInterface public interface ConditionChecker { boolean check(Teste teste); // 逻辑或 default ConditionChecker or(ConditionChecker other) { return teste -> this.check(teste) || other.check(teste); } // 逻辑与 default ConditionChecker and(ConditionChecker other) { return teste -> this.check(teste) && other.check(teste); } // 逻辑非 default ConditionChecker not() { return teste -> !this.check(teste); } }
这样组合条件时可读性更强:
ConditionChecker blueOrSad = TesteConditions::isBlue .or(TesteConditions::isSad); ConditionChecker blueAndNotSad = TesteConditions::isBlue .and(TesteConditions::isSad.not());
完全满足你的两个需求:
- 无需为每个条件组合单独实现Model类
- 检查方法直接操作
Teste对象,避免重复传递字符串参数
内容的提问来源于stack exchange,提问作者Antônio
相关产品推荐
相关产品推荐

