Skip to content

Instantly share code, notes, and snippets.

@EWOTE
Last active April 23, 2017 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EWOTE/f8c72e6ae7cda71c2fc0e68665c0b881 to your computer and use it in GitHub Desktop.
Save EWOTE/f8c72e6ae7cda71c2fc0e68665c0b881 to your computer and use it in GitHub Desktop.
// 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 {
private final int servingSize;
private final int servings;
private int calories;
private int fat;
private int sodium;
private int carbohydrate;
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 sodium(int val) {
sodium = val;
return this;
}
public Builder carbohydrate(int val) {
carbohydrate = val;
return this;
}
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder) {
servings = builder.servings;
servingSize = builder.servingSize;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
public static void main(String[] args) {
// вот как выглядит код клиента
NutritionFacts cocaCola = new Builder(340,11).calories(200).fat(30).carbohydrate(40).build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment