The Builder pattern simulates named optional parameters(Java)

时间:2020-12-30 22:20:55

the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

/**
* Created by xfyou 2017/5/27 14:41 14:42.
* The Builder pattern simulates named optional parameters
*/
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(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
} public Builder calories(int val) {
this.calories = val;
return this;
} public Builder carbohydrate(int val) {
this.carbohydrate = val;
return this;
} public Builder sodium(int val) {
this.sodium = val;
return this;
} public NutritionFacts build() {
return new NutritionFacts(this);
}
} public NutritionFacts(Builder builder) {
this.calories = builder.calories;
this.carbohydrate = builder.carbohydrate;
this.fat = builder.fat;
this.servings = builder.servings;
this.servingSize = builder.servingSize;
this.sodium = builder.sodium;
} public int getServingSize() {
return servingSize;
} public int getServings() {
return servings;
} public int getCalories() {
return calories;
} public int getFat() {
return fat;
} public int getSodium() {
return sodium;
} public int getCarbohydrate() {
return carbohydrate;
}
}