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

后端 未结 4 1676
孤街浪徒
孤街浪徒 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 11:03

    To add to what the others have written:

    In order to make your class immutable, you need to make parameterMap variable immutable as well. You can do that when the ModelInput class is instantiated:

    private ModelInput(Builder builder){
      this.userid = builder.userid;
      this.clientid = builder.clientid;
      this.pref = builder.pref;
      this.parameterMap = Collections.unmodifiableMap(builder.parameterMap);
      this.timeout = builder.timeout;
      this.debug = builder.debug;
    }
    

    Notice the use of Collections.unmodifiablemap();

    You'll also need to make your Preference instance immutable, or at least make it known that it is in fact not immutable.

提交回复
热议问题