我的下面的Builder模式是线程安全的,并确保在使用ImmutableMap和ImmutableList Guava类分配给parameterMap
类后,dataType
和InputKeys
无法修改。< / p>
public final class InputKeys {
private final long userid;
private final long clientid;
private final List<String> holderEntry;
private static final ImmutableList<String> DEFAULT_TYPE = ImmutableList.of("HELLO");
private InputKeys(Builder builder) {
this.userid = builder.userId;
this.clientid = builder.clientid;
this.holderEntry = builder.holderEntry.build();
}
public static class Builder {
protected final long clientid;
protected long userid;
protected ImmutableList.Builder<String> holderEntry = ImmutableList.<String>builder().addAll(DEFAULT_TYPE);
public Builder(InputKeys key) {
this.clientid = key.clientid;
this.userid = key.userid;
this.holderEntry = ImmutableList.<String> builder().addAll(key.holderEntry);
}
public Builder(long clientid) {
this.clientid = clientid;
}
public Builder setUserId(long userid) {
this.userid = Long.valueOf(userid);
return this;
}
public Builder addEntry(List<String> holderEntry) {
this.holderEntry.addAll(holderEntry);
return this;
}
public InputKeys build() {
return new InputKeys(this);
}
}
// getters here
}
现在我有两个要求:
addEntry
方法,那么我的holderEntry
列表中只应包含HELLO。addEntry
方法,我只想使用他们传递的列表。根据我目前的设计,让我们说'如果有人传递了包含WORLD字符串的新List,那么我的holderEntry
变量包含两个值,一个是HELLO和WORLD,这是错误的。在这种情况下,我想只拥有WORLD。我该如何解决这个问题?
答案 0 :(得分:1)
为什么不在构建器中默认为holderEntry
为空?
在InputKeys
的构造函数中,您将检查builder.holderEntry
是否为空。如果是,您可以将this.holderEntry
设置为DEFAULT_TYPE
。它也会更高效,更清洁。
在Builder
:
protected ImmutableList.Builder<String> holderEntry = ImmutableList.<String>builder();
在InputKeys
构造函数中:
List<String> holderEntry = builder.holderEntry.build();
this.holderEntry = holderEntry.isEmpty() ? DEFAULT_TYPE : holderEntry;