第二条 遇到多个构造器参数时要考虑用构建器

构造方法中传递的参数一般是必要参数,如果一个类,有必要的属性,还有可选的属性,那可用Builder构造器 建立对应的类

例:类Nutrition 有必要属性servings,servings,可选属性为calories,fat,sodium,carbohydrate

public class Nutrition {
	//parameters
	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 {
		//requierd parameters
		private final int servingSize;
		private final int servings;
		//optional parameters
		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 var) {
			this.calories = var;
			return this;
		}
		public Builder fat(int var) {
			this.fat = var;
			return this;
		}
		public Builder sodium(int var) {
			this.sodium = var;
			return this;
		}
		public Builder carbohydrate(int var) {
			this.carbohydrate = var;
			return this;
		}
		//Don't forgot
		public Nutrition build() {
			return new Nutrition(this);
		}
		
	}
	//construction
	private Nutrition(Builder builder) {
		this.servingSize = builder.servings;
		this.servings = builder.servings;
		this.calories = builder.calories;
		this.fat = builder.fat;
		this.sodium = builder.sodium;
		this.carbohydrate = builder.carbohydrate;
	}
		
}


代码分析:
(1)写Nutrition 类的属性
为减少类成员的可访问性,将所有Nutrition 类属性定义为private final类型

(2)建立Builder类,写Builder类的属性

定义Builder为public static class,写属性时区分必要或可选,必要用private final类型,可选用private,并且定义简单的初值,假定为0、null或其他

(3)处理必要属性,建立Builder类的构造方法
将必要的属性放入Builder的属性中,例子中为servings和servingSize

(4)处理可选属性,建立Builder类的其他类
每个方法先修改calories、fat等参数,然后返回Builder自身

(5)builder方法

先调用Nutrition 的构造方法,将自己传过去,返回一个new Nutrition。此方法我认为是很容易忘记的地方,最起码我写时忘了汗  ,Builder完成。

(6)完善Nutrition的构造方法
将 Builder中的所有属性copy到自身中,全是this.xxx = builder.xxx

(7)方法调用
Nutrition n = new Nutrition.Builder(100,200).fat(230).sodium(120).build();

第二条 遇到多个构造器参数时要考虑用构建器,此方法好像用的不多,使用范围不了。。。

你可能感兴趣的:(java)