I have recently read Effective Java and I found that the Builder Pattern (item #2) is very interesting. However, I have a question: why should we create a static builder when we could do this:
// JavaBeans Pattern
public class NutritionFacts {
private int servingSize;
private int servings;
private int calories;
private int fat;
public NutritionFacts() {
}
public NutritionFacts servingSize(int val) {
this.servingSize = val;
return this;
}
public NutritionFacts servings(int val) {
this.servings = val;
return this;
}
public NutritionFacts calories(int val) {
this.calories = val;
return this;
}
public NutritionFacts fat(int val) {
this.fat = val;
return this;
}
}
//usage
NutritionFacts nf = new NutritionFacts().servingSize(5).servings(4).calories(3).fat(1);
When doing this, we could avoid creating 2 instances.
Could you please explain what the problems are with this method?