Read Notes:[Effective Java] Consider a builder when faced with many constructor parameters

  • The Telescoping Constructor pattern works, but it is hard to write client code when there are many parameters, and harder still to read it.

  • The JavaBeans pattern is split across multiple calls, a JavaBean may be in an inconsistent state partway through its construction. The JavaBeans pattern precludes the possibility of making a class immutable.

  • The Builder pattern simulates named optional parameters as found in Ada and Python. (builder pattern must first create its builder.  And it is more verbose than the telescoping constructor pattern.)

// Builder Pattern
public class NutritionFacts {
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;
    public static class Builder {
        // Required parameters
        private final int servingSize;
        private final int servings;
        // Optional Parameters - initialized to default values
        private int calories          = 0;
        private int fat                  = 0;
        private int carbohydrate = 0;
        private int sodium           = 0;
        public Builder calories(int val) {
            calories = val;
            return this;
        } 
        public Builder fat(int val) {
            fat = val;
            return this;
        }
        public Builder carbohydrate(int val) {
            carbohydrate = val;
            return this;
        }
        public Builder sodium(int val) {
            sodium = val;
            return this;
        }
        public NutritionFacts buid() {
            return new NutritionFacts(this);
        }
    }
    private NutritionFacts(Builder builder) {
        servingSize   = builder.servingSize;
        servings      = builder.servings;
        calories      = builder.calories;
        fat           = builder.fat;
        sodium        = builder.sodium;
        carbohydrate  = builder.carbohydrate;
    }
}
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build();


   In summary, the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters, especially if most of those parameters are optional. Client code is much easier to read and write with builders than with the traditional telescoping constructor pattern, and builders are much safer than JavaBeans.

你可能感兴趣的:(java,Pattern,javabean,builder,builder,effective,Constructor,item,2,telescoping)