测试代码
一般带参数的构造函数为new Constructor(参数1,参数2),但是当参数为5个或者10或者更多的时候这种方式就会不太好,因为可能发生有些参数我们不需要传递值,但是不得不传值的情况,这时候就要用到构建器,如下:
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;
/**
* 构建器(在多个参数的时候使用)
* @param servingSize
* @param servings
*/
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(){
return new NutritionFacts(this);
}
}
public NutritionFacts(Builder builder){
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
public static void main(String [] args){
//灵活的配置多个参数,一个构建器可以创建多个对象
NutritionFacts coca = new NutritionFacts.Builder(5, 3)
.calories(2)
.fat(3)
.sodium(4)
.carbohydrate(7)
.builder();
System.out.println(""+coca.servingSize+coca.servings+coca.calories+coca.fat+coca.sodium+coca.carbohydrate);
}
}