I was reading about the benefits of the builder pattern here: http://drdobbs.com/java/208403883?pgno=2
I was wondering about the viability of the following, which seems simpler.
public class NutritionFactParams {
private int servingSize;
private int servings;
private int fat_ = 0;
private int sodium_ = 0;
NutritionFactParams(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
NutritionFactParams fat(int fat) {
this.fat_ = fat;
return this;
}
NutritionFactParams sodium(int sodium) {
this.sodium_ = sodium;
return this;
}
}
public class NutritionFacts {
public NutritionFacts(NutritionFactParams params) {
// copy values across, or store NutritionFactParams as member
}
}
public class Main {
public static void main(String args[]) {
NutritionFacts n = new NutritionFacts(new NutritionFactParams(1,2).fat(23).soduim(10));
}
}
This is basically the builder pattern, except that the NutritionFacts constructor is public not private, we don’t have a static Builder class inside of NutritionFacts, and there is no build() method on the builder. There’s no alternate or default constructor so you can’t build NutritionFacts without first constructing a NutritionFactsParams.
The difference is not big, but there is one important differences i can think of:
If you use builder, the client code does not need to know what Impl you actually return on build() meaning that, you have flexibility to return different Impls depending on the configuration (builder). On the other hand, using constructor, the client have to explicitly create the Impl.