我们假设我有以下类试图成为不可变的
public class Computation {
private final Operation operation;
private final double epsilon;
public Computation(Operation operation) {
this.operation = operation;
//Default value
epsilon = 0.01;
}
public Computation(Operation operation double epsilon) {
this(operation);
//Won't compile as epsilon is final and is set by the other constructor
this.epsilon = epsilon;
}
}
而且,为了这个问题,让我们假设我不想在这个类中使用构建器(这将解决问题)。
所以问题是:
有没有办法在不将最终修饰符移到epsilon并保留两个构造函数的情况下实现此行为?
即没有像
这样的事情 public class Computation {
private final Operation operation;
private final double epsilon;
public Computation(Operation operation Double epsilon) {
this(operation);
this.epsilon = (epsilon == null) ? 0.01 : epsilon;
}
}
并且不使用构建器
public class Computation {
private final Operation operation;
private final double epsilon;
private Computation(Builder builder) {
this.operation = builder.operation;
this.epsilon = builder.epsilon;
}
public static class Builder {
private final Operation operation;
//Default value
private double epsilon = 0.01;
public Builder(Operation operation) {
this.operation = operation;
}
public Builder epsilon(double epsilon) {
this.epsilon = epsilon;
return this;
}
public Computation build() {
return new Computation(this);
}
}
答案 0 :(得分:7)
是 - 反转逻辑,以便更少参数的构造函数使用 more 调用:
public Computation(Operation operation) {
this(operation, 0.01);
}
public Computation(Operation operation, double epsilon) {
this.operation = operation;
this.epsilon = epsilon;
}
基本上这样你就可以得到很多构造函数,这些构造函数都只委托给一个完成所有实际工作的“真正”构造函数。