我有下面的Builder模式,该模式是线程安全的,并且还确保通过使用ImmutableMap和ImmutableList Guava类将parameterMapdataType分配给InputKeys类后,不能对其进行修改。

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。如何解决此问题?

最佳答案

为什么在构建器中默认不将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;

08-17 19:43