How to improve the builder pattern?

后端 未结 10 897
野性不改
野性不改 2020-12-02 10:34

Motivation

Recently I searched for a way to initialize a complex object without passing a lot of parameter to the constructor. I tried it with the builder pattern,

10条回答
  •  一向
    一向 (楼主)
    2020-12-02 11:14

    Why don't you put "needed" parameters in the builders constructor?

    public class Complex
    {
    ....
      public static class ComplexBuilder
      {
         // Required parameters
         private final int required;
    
         // Optional parameters
         private int optional = 0;
    
         public ComplexBuilder( int required )
         {
            this.required = required;
         } 
    
         public Builder setOptional(int optional)
         {
            this.optional = optional;
         }
      }
    ...
    }
    

    This pattern is outlined in Effective Java.

提交回复
热议问题