/**
* 如果类的构造器或者静态工厂中具有多个参数,设计这种类时,Builder模式就是种不错的选择,特别是当大多数参数都是可选的时候。
* 与使用传统的重叠构造器模式相比,使用Builder模式的客户端代码将更易于阅读和编写,构建器也比JavaBeans更加安全。
*
* @author 刘向峰
*
*/
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 {
// 必须的参数,final保证了它必须被赋值
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;
}
/**
*
* @param val
* 对可选项进行赋值
* @return Builder对象,以进行链式调用赋值函数
*/
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;
}
/**
* 创建获取对象方法,将自己(Builder)作为参数传入
*
* @return NutritionFacts对象
*/
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
/**
* 私有化构造函数,保证对同一个对象进行操作
*
* @param builder传入构造器进行赋值
*/
private NutritionFacts(Builder builder) {
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
/**
* 测试方法
*
* @param args
*/
public static void main(String[] args) {
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8)
.calories(100).sodium(35).carbohydrate(27).build();
}
}
时间: 2024-10-18 03:20:11