实现说明
活动部件是类 RetryPolicy、Policy、Builder和函数 Policy、builder、maxAttempts、initialDelay。
失败路径是显式的——守卫条件成立就抛出 IllegalArgumentException。
使用要点
- 演示输出是带标签的(
rejected:),每个操作都会留下自己的一行标注。 - 执行文件,
main会按顺序走完builder、maxAttempts、initialDelay、build。
常见问题
输入不合法时代码会怎么表现?
在真正开工之前就会抛出 IllegalArgumentException——请在调用点处理,或有意向上传播。
运行「Record 构建器与不变量校验」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 rejected: 标签标明各步骤。
主要签名是 public record Policy(int maxAttempts, Duration initialDelay, double backoffMultiplier)
核心语句
throw new IllegalArgumentException("maxAttempts must be 1..10: " + maxAttempts);
throw new IllegalArgumentException("backoffMultiplier must be >= 1.0");
throw new IllegalArgumentException("initialDelay must be positive");
代码示例
import java.time.Duration;
public class RetryPolicy {
public record Policy(int maxAttempts, Duration initialDelay, double backoffMultiplier) {
public Policy {
// 紧凑构造器:非法实例无法存在
if (maxAttempts < 1 || maxAttempts > 10) {
throw new IllegalArgumentException("maxAttempts must be 1..10: " + maxAttempts);
}
if (initialDelay.isNegative() || initialDelay.isZero()) {
throw new IllegalArgumentException("initialDelay must be positive");
}
if (backoffMultiplier < 1.0) {
throw new IllegalArgumentException("backoffMultiplier must be >= 1.0");
}
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private int maxAttempts = 3;
private Duration initialDelay = Duration.ofMillis(200);
private double backoffMultiplier = 2.0;
public Builder maxAttempts(int value) {
this.maxAttempts = value;
return this;
}
public Builder initialDelay(Duration value) {
this.initialDelay = value;
return this;
}
public Builder backoffMultiplier(double value) {
this.backoffMultiplier = value;
return this;
}
public Policy build() {
return new Policy(maxAttempts, initialDelay, backoffMultiplier);
}
}
}
public static void main(String[] args) {
RetryPolicy.Policy policy = RetryPolicy.Policy.builder()
.maxAttempts(5)
.initialDelay(Duration.ofMillis(100))
.build();
System.out.println(policy);
try {
RetryPolicy.Policy.builder().maxAttempts(0).build();
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}