Item 2 (Builder), Effective Java
15922 ワード
コンストラクション関数に多くのパラメータがある場合は、コンストラクタを考慮します。
コンストラクション関数を使用して作成する場合は、パラメータが多い場合にも使用できます。
Telescotting Constructor Pattern(レイヤジェネレータアレイ単位)
次のコード
public class Test{
private final String fieldA;
private String fieldB;
private String fieldC;
private String fieldD;
public Test(String fieldA){ ... }
public Test(String fieldA, String fieldB){ ... }
public Test(String fieldA, String fieldB, String fieldC){ ... }
public Test(String fieldA, String fieldB, String fieldC, String fieldD){ ... }
}
public class Test{
private String fieldA;
private String fieldB;
public Test(String fieldA, String fieldB){ ... }
}
Test test = new Test(fieldB, fieldA); // 두 인자의 순서가 바뀜 하지만 컴파일 오류는 없음
JavaBeans Pattern(JavaBeansモード)
オブジェクトを作成したら、
public class Test{
private String fieldA;
private String fieldB;
public Test(){ ... };
public void setFieldA(String fieldA){ ... }
public void setFieldB(String fieldB){ ... }
}
Test test = new Test();
test.setFieldA("");
test.setFieldB("");
Builder Patternは最高の代替製品です
オブジェクト内にclassを作成します。
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 = 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(Builder builder) {
this.servingSize = builder.servingSize;
this.servings = builder.servings;
this.calories = builder.calories;
this.fat = builder.fat;
this.sodium = builder.sodium;
this.carbohydrate = builder.carbohydrate;
}
}
この2つの方法の利点が結合している。
注意点
Reference
この問題について(Item 2 (Builder), Effective Java), 我々は、より多くの情報をここで見つけました https://velog.io/@nnagman/Item-2-Builder-Effective-Javaテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol