オブジェクト生成、ビルダーパターンのサンプル
This file contains 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
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 = 0; | |
private int fat = 0; | |
private int sodium = 0; | |
private int carbohydrate = 0; | |
public Builder(int servingsSize, int servings) { | |
this.servingSize = servingsSize; | |
this.servings = servings; | |
} | |
public Builder calories(int calories) { | |
this.calories = calories; | |
return this; | |
} | |
public Builder fat(int fat) { | |
this.fat = fat; | |
return this; | |
} | |
public Builder sodium(int sodium) { | |
this.sodium = sodium; | |
return this; | |
} | |
public Builder carbohydrate(int carbohydrate) { | |
this.carbohydrate = carbohydrate; | |
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; | |
} | |
} | |
class Main { | |
public static void main(String[] args) { | |
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8) | |
.calories(100) | |
.sodium(35) | |
.build(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment