构建模式-Builder

/**
 *构建者模式使用场景是如果类的构造器或者静态工程中具有多个参数时,
 *使用构造器或者静态工程都比较麻烦;当然也可以用JavaBeans的方式创建对象,
 *但是这种方式使得对象的状态有可能不一致
 */
public class Builder_model {
	public static void main(String[] args) {
		NutritionFacts nu = new NutritionFacts.NBuilder(1, 2).calories(3).sodium(4).fat(1).build();
		System.out.println(nu);
	}
}
/**构建者接口**/
interface Builder<T> {
	public T build();
}
/**一个类对应自己的构建器,可以定义在类的内部**/
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 carbohyrate;
	private NutritionFacts(NBuilder builder) {
		servingSize = builder.servingSize;
		servings = builder.servings;
		calories = builder.calories;
		fat = builder.fat;
		sodium = builder.sodium;
		carbohyrate = builder.carbohyrate;
	}
	public static class NBuilder implements Builder<NutritionFacts> {
		/**假设:构建NUtritionFacts必须的参数**/
		private final int servingSize;
		private final int servings;
		/**可选参数**/
		private  int calories=0;
		private  int fat=0;
		private  int sodium=0;
		private  int carbohyrate=0;
		
		public NBuilder(int servingSize, int servings) {
			this.servingSize = servingSize;
			this.servings = servings;
		}
		/**可选属性的赋值**/
		public NBuilder calories(int val) {
			calories = val; return this;
		}
		public NBuilder fat(int val) {
			fat = val; return this;
		}
		public NBuilder carbohyrate(int val) {
			carbohyrate = val; return this;
		}
		public NBuilder sodium(int val) {
			sodium = val; return this;
		}
		@Override
		public NutritionFacts build() {
			return new NutritionFacts(this);
		}
	}
	@Override
	public String toString() {
		return this.servingSize+this.servings+this.sodium+"";
	}
}



你可能感兴趣的:(构建模式-Builder)