How to use Builder pattern as described by Joshua Bloch's version in my ModelInput class?

后端 未结 4 1723
孤街浪徒
孤街浪徒 2021-01-23 10:32

I am trying to use Builder Pattern for my below class.. Initially I was using constructor of my class to set all the parameters but accidentally I came across Builder pattern an

4条回答
  •  日久生厌
    2021-01-23 10:51

    Builder constructor must have the mandatory parameters. So, in your case, if userId, clientId and parameterMap are mandatory, we will have something like that:

    public final class ModelInput {
    
        private long userid;
        private long clientid;
        private long timeout = 500L;
        private Preference pref;
        private boolean debug;
        private Map parameterMap;
    
        public ModelInput(Builder builder) {
            this.userid = builder.userId;
            this.clientid = builder.clientId;
            this.pref = builder.preference;
            this.parameterMap = builder.parameterMap;
            this.timeout = builder.timeout;
            this.debug = builder.debug;
        }
    
        public static class Builder {
            private long userId;
            private long clientId;
            private Preference preference;
            private boolean debug;
            private Map parameterMap;
    
            public Builder(long userId, long clientId, Map parameterMap) {
                this.userId = userId;
                this.clientId = clientId;
                this.parameterMap = parameterMap;
            }
    
            public Builder preference(Preference preference) {
                this.preference = preference;
                return this;
            }
    
            public Builder debug(boolean debug) {
                this.debug = debug;
                return this;
            }
    
            public Builder timeout(long timeout) {
                this.timeout = timeout;
                return this;
            }
    
            ...
    
            public ModelInput build() {
                return ModelInput(this);
            }
        }
    
        // ModelInput getters / setters
    }
    

    And this is how to use your builder class:

    String paramMap = new HashMap();
    paramMap.put("attribute", "segmentation");
    
    ModelInput.Builder builder = new ModelInput.Builder(109739281L, 20L, paramMap);
    builder.preference(Preference.SECONDARY).timeout(1000L).debug(true);
    
    ModelInput modelInput = builder.build();
    

    Hope this helps :)

提交回复
热议问题