Created
September 12, 2011 23:00
-
-
Save shouichi/1212717 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Builder pattern example from Effective Java. | |
*/ | |
public final 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 final class Builder { | |
// Required | |
private final int servingSize; | |
private final int servings; | |
// Optional | |
private int calories = 0; | |
private int fat = 0; | |
private int sodium = 0; | |
private int carbohydrate = 0; | |
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) { | |
servingSize = builder.servingSize; | |
servings = builder.servings; | |
calories = builder.calories; | |
fat = builder.fat; | |
sodium = builder.sodium; | |
carbohydrate = builder.carbohydrate; | |
} | |
@Override | |
public String toString() { | |
return "servingSize: " + servingSize + "\n" + | |
"servings: " + servings + "\n" + | |
"calories: " + calories + "\n" + | |
"fat: " + fat + "\n" + | |
"sodium: " + sodium + "\n" + | |
"carbohydrate: " + carbohydrate; | |
} | |
public static void main(final String[] args) { | |
NutritionFacts cocoCola = new NutritionFacts.Builder(240, 8). | |
calories(100).sodium(35).carbohydrate(27).build(); | |
System.out.println(cocoCola); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment