java_可变参数构造器 Bulder模式

package com.test1.www;

class NutritionFacts {
	//必须
	private int servingSize;
	private int servings;
	//可选, Build类必须初始化
	private int calories;
	private int fat;
	private int sodium;
	private int carboohydrate;
	
	public int getServingSize() {
		return servingSize;
	}


	public int getServings() {
		return servings;
	}


	public int getCalories() {
		return calories;
	}


	public int getFat() {
		return fat;
	}


	public int getSodium() {
		return sodium;
	}


	public int getCarboohydrate() {
		return carboohydrate;
	}


	static class Builder {
		private int servingSize;
		private int servings;
		private int calories=0;
		private int fat=0;
		private int sodium=0;
		private int carboohydrate=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 sodium(int val) {
			sodium = val;
			return this;
		}

		public Builder carboohydrate(int val) {
			carboohydrate = val;
			return this;
		}
		public NutritionFacts build() {
			return new NutritionFacts(this);
		}

	}

	
	public NutritionFacts(Builder builder){
		servingSize = builder.servingSize;
		 calories=builder.calories;
		 fat=builder.fat;
		 sodium = builder.sodium;;
		 carboohydrate= builder.carboohydrate;
		
	}
}

public class Demo2 {
	public static void main(String[] args) {
		NutritionFacts nt = new NutritionFacts.Builder(240, 8).calories(20).carboohydrate(30).fat(20).sodium(2).build();
		
		System.out.println(nt.getServingSize());
		System.out.println(nt.getServings());
		System.out.println(nt.getCalories());
		System.out.println(nt.getFat());
		System.out.println(nt.getCarboohydrate());
		System.out.println(nt.getSodium());
	}
}


posted @ 2013-12-26 01:02  MrMrCash  阅读(345)  评论(0编辑  收藏  举报