我有一个构建器模式,其中很可能我的所有参数都是强制性的,因此我创建了一个长构造器,如下面的代码所示。
public final class ResponseHolder {
// all below six are related to response information
private final String response;
private final boolean isLinking;
private final TypeHold typeOfId;
private final long userTimeInMs;
private final long userLmdInDays;
private final String maskInfo;
// below two are related to error handling
private final ErrorCode error;
private final StatusCode status;
private ResponseHolder(Builder builder) {
this.response = builder.response;
this.isLinking = builder.isLinking;
this.typeOfId = builder.typeOfId;
this.userTimeInMs = builder.userTimeInMs;
this.userLmdInDays = builder.userLmdInDays;
this.maskInfo = builder.maskInfo;
this.error = builder.error;
this.status = builder.status;
}
public static class Builder {
protected final String response;
protected final TypeHold typeOfId;
protected final String maskInfo;
protected final ErrorCode error;
protected final StatusCode status;
protected final boolean isLinking;
protected final long userTimeInMs;
protected final long userLmdInDays;
public Builder(String response, TypeHold typeOfId, String maskInfo, ErrorCode error,
StatusCode status, boolean isLinking, long userTimeInMs, long userLmdInDays) {
this.response = response;
this.typeOfId = typeOfId;
this.maskInfo = maskInfo;
this.error = error;
this.status = status;
this.isLinking = isLinking;
this.userTimeInMs = userTimeInMs;
this.userLmdInDays = userLmdInDays
}
public ResponseHolder build() {
return new ResponseHolder(this);
}
}
// getters here
}
现在我很困惑,当所有参数都是强制性的,那么它有什么用呢?有没有更好的方法来表示我上面的 Builder 模式?可能在逻辑上将传递给它们自己的类的参数分组,以减少传递给构建器构造函数的参数数量?
虽然拥有单独的对象可以大大简化事情,但如果不熟悉代码,也会使事情变得有点难以理解。我可以做的一件事是将所有参数移动到它们自己的addParam(param)
方法中,然后build()
在运行时对方法中所需的参数执行验证?
我应该在这里遵循什么最佳实践,我可以在这里使用什么更好的方法?