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

后端 未结 4 1677
孤街浪徒
孤街浪徒 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:48

    I am not familiar with the book you are referencing, but I would suggest reading the post of wikipedia regarding the Builder pattern which is rather straight forward.

    An implementation could be:

    public final class ModelInput {
    
    ...
    
        public static class Builder {
            private long userid;
            ...    
    
            public Builder(long userid) {
                this.userid = userid;
            }
    
           ...
    
            public ModelInput build() {
                return new ModelInput(this);
            }
        }
    
        private ModelInput(Builder builder){
            this.userid = builder.userid;
            this.clientid = builder.clientid;
            this.pref = builder.pref;
            this.parameterMap = builder.parameterMap;
            this.timeout = builder.timeout;
            this.debug = builder.debug;
        }
    
    ...
    }
    

    Then when you want to initialize an object, you would call

    ModelInput model = new ModelInput.Builder(...).build();
    

    Regarding the validation process, it would be essentially the same as it would be made by checking the values (either in the constructor, or in the build method).

    Hope I helped!

提交回复
热议问题