【设计模式】建造者

 

package pattern.builder;

public class BuilderDemo {
	public static void main(String[] args) {
		
		NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8)
				.calories(100).sodium(35).carbohydrate(27).build();
		
		System.out.println(cocaCola);
	}
}

/**
 * 建造者模式
 * 	1.构造函数参数很多的时候,要创建一个对象非常的麻烦。因为对每个参数赋值的顺序很容易出错。
 *  2.使用本模式可以避免冗长的setter调用 
 * 
 * 关键:
 * 	1.必须的参数仍通过Builder构造方法传入
 *  2.可选参数则通过"链式调用"进行设置
 *  3.所有需要的属性设置完成后,调用build()方法返回最终的对象
 */
// Builder Pattern
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 {
		// Required parameters
		private final int servingSize;
		private final int servings;
		// Optional parameters - initialized to default values
		private int calories = 0;
		private int fat = 0;
		private int carbohydrate = 0;
		private int sodium = 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 carbohydrate(int val) {
			carbohydrate = val;
			return this;
		}

		public Builder sodium(int val) {
			sodium = val;
			return this;
		}
		
		//last step: use Builder's attribute to create the instance!
		public NutritionFacts build() {
			return new NutritionFacts(this);
		}
	}

	private NutritionFacts(Builder builder) {
		servingSize = builder.servingSize;
		servings = builder.servings;
		calories = builder.calories;
		fat = builder.fat;
		sodium = builder.sodium;
		carbohydrate = builder.carbohydrate;
	}

	@Override
	public String toString() {
		return "NutritionFacts [servingSize=" + servingSize + ", servings="
				+ servings + ", calories=" + calories + ", fat=" + fat
				+ ", sodium=" + sodium + ", carbohydrate=" + carbohydrate + "]";
	}
	
	
}

 

你可能感兴趣的:(设计模式)