I am using the Java builder pattern provided by Joshua Bloch. Sometimes I find certain fields that are more expensive to initialize using the default value compared to primitive types.
Therefore, my strategy is this.
- I delay the default initialization operation for these fields.
- During the build, I will only initialize them by default, unless they were previously installed by the caller.
I'm not sure if this is good for this? Are there any tricks? For example, thread safety issues? So far I do not see any problems with this.
package sandbox;
import java.util.Calendar;
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;
private final java.util.Calendar calendar;
public static class Builder {
private final int servingSize;
private final int servings;
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0;
private java.util.Calendar calendar = null;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
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 build() {
if (this.calendar == null) {
this.calendar = Calendar.getInstance();
}
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;
calendar = builder.calendar;
}
}
source
share