以下是实现链式条件检查的Java方法,采用函数式风格设计。代码包含一个Chainable
类,支持连续的check
方法和多个终止操作(如then
, orElse
等),满足在条件为false时中断链式调用并返回默认值的需求:
import java.util.Optional;
import java.util.function.Supplier;
public class Chainable {
private boolean shouldProceed = true;
private Chainable() {}
// 起始方法
public static Chainable start() {
return new Chainable();
}
// 核心检查方法:满足条件则继续,不满足则中断后续链式调用
public Chainable check(Supplier<Boolean> conditionSupplier) {
if (shouldProceed) {
this.shouldProceed = conditionSupplier.get();
}
return this;
}
// 简化版检查(直接使用布尔值)
public Chainable check(boolean condition) {
return check(() -> condition);
}
// 执行操作并返回结果(中断时返回null)
public <R> R then(Supplier<R> supplier) {
return shouldProceed ? supplier.get() : null;
}
// 执行无返回值操作
public void then(Runnable runnable) {
if (shouldProceed) runnable.run();
}
// 执行操作并返回Optional(中断时返回空Optional)
public <R> Optional<R> thenOptional(Supplier<R> supplier) {
return shouldProceed ? Optional.ofNullable(supplier.get()) : Optional.empty();
}
// 中断时返回指定默认值
public <R> R orElse(Supplier<R> supplier, R defaultValue) {
return shouldProceed ? supplier.get() : defaultValue;
}
// 中断时执行备选操作
public <R> R orElseGet(Supplier<R> mainSupplier, Supplier<R> backupSupplier) {
return shouldProceed ? mainSupplier.get() : backupSupplier.get();
}
// 中断时抛出指定异常
public <R> R orElseThrow(Supplier<R> supplier, Supplier<? extends RuntimeException> exceptionSupplier) {
if (!shouldProceed) throw exceptionSupplier.get();
return supplier.get();
}
}
使用示例
public static void main(String[] args) {
// 示例1:条件全部满足时返回计算结果
Integer result1 = Chainable.start()
.check(() -> 10 > 5)
.check(() -> 20 > 15)
.then(() -> 10 + 20);
System.out.println("Result 1: " + result1); // 输出 30
// 示例2:条件不满足时返回默认值
String result2 = Chainable.start()
.check(false) // 直接中断
.check(() -> {
System.out.println("此代码不会执行");
return true;
})
.orElse(() -> "成功", "失败");
System.out.println("Result 2: " + result2); // 输出 "失败"
// 示例3:中断时抛出异常
try {
Chainable.start()
.check(3 > 5)
.orElseThrow(
() -> "计算结果",
() -> new IllegalStateException("条件检查失败")
);
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage()); // 输出异常信息
}
// 示例4:无返回值的操作
Chainable.start()
.check(() -> true)
.then(() -> System.out.println("操作被执行")); // 正常输出
// 示例5:使用Optional避免null
Optional<String> optional = Chainable.start()
.check(false)
.thenOptional(() -> "不会执行");
System.out.println("Optional: " + optional.isPresent()); // 输出 false
}
关键特性:
- 链式中断机制 - 当任何
check
失败时,后续链式调用自动跳过 - 延迟计算 - 使用
Supplier<Boolean>
避免不必要的条件计算 - 多终止操作 :
then()
:返回结果或nullthenOptional()
:返回安全容器orElse()
:提供默认值orElseThrow()
:中断时抛出异常
- 类型安全 - 通过泛型支持任意返回类型
- 空值安全 - Optional包装避免NPE
此实现通过函数式接口保持代码简洁,同时提供灵活的中断处理和多种返回策略,符合现代Java编程风格。