下面是我的构建器类,其中两个字段是必需的,它们是userId
和clientId
。
public final class InputKeys {
private final long userId;
private final int clientId;
private final long timeout;
private final Preference preferences;
private final boolean debugFlag;
private final Map<String, String> attributeMap;
private InputKeys(Builder builder) {
this.userId = builder.userId;
this.clientId = builder.clientId;
this.preferences = builder.preference;
this.attributeMap = builder.attributeMap;
this.timeout = builder.timeout;
this.debugFlag = builder.debugFlag;
}
public static class Builder {
protected final long userId;
protected final int clientId;
protected long timeout = 500L;
protected Preference preference;
protected boolean debugFlag;
protected Map<String, String> attributeMap;
public Builder(long userId, int clientId) {
this.userId = userId;
this.clientId = clientId;
}
public Builder attributeMap(Map<String, String> attributeMap) {
this.attributeMap = attributeMap;
return this;
}
public Builder preference(Preference preference) {
this.preference = preference;
return this;
}
public Builder debugFlag(boolean debugFlag) {
this.debugFlag = debugFlag;
return this;
}
public Builder timeout(long timeout) {
this.timeout = timeout;
return this;
}
public InputKeys build() {
return new InputKeys(this);
}
}
//getters here
}
现在我将像这样调用这个构建器类 -
InputKeys keys = new InputKeys.Builder(12000L, 33L).build();
但也有可能有人会传递错误的输入值,例如他们传递负的 userId 和负的 clientId、负的超时值或空的属性映射。如何在我的构建器类中处理这种情况?
如果我对 中的每个变量都有 IllegalArgumentcheck if else if block
,那么我的整个 Builder 类会被 IllegalArgumentException 检查淹没吗?
有没有更好的方法来做到这一点?