역학 디자인 모델 5 건축 모델 (Builder)

2889 단어 디자인 모드
여러 구조 기 파라미터 (Constructor Parameters) 를 만 났 을 때 구축 기 (Builder) 를 사용 하 는 것 을 고려 해 야 합 니 다.

//   
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 {
		
		 //     
        private final int servingSize;
        private final int servings;
        //     
        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 calories) {
        	this.calories = calories;
        	return this;
        }
        
        public Builder sodium(int sodium) {
        	this.sodium = sodium;
        	return this;
        }
        
        public Builder fat(int fat) {
        	this.fat = fat;
        	return this;
        }
        
        public Builder carbohydrate(int carbohydrate) {
        	this.carbohydrate = carbohydrate;
        	return this;
        }
        //           
        public NutritionFacts build() {
        	return new NutritionFacts(this);
        }
	}
	//     
	private NutritionFacts(Builder builder) {
		this.servingSize = builder.servingSize;
		this.servings = builder.servings;
		this.calories = builder.calories;
		this.fat = builder.fat;
		this.sodium = builder.sodium;
		this.carbohydrate = builder.carbohydrate;
	}
	
	@Override
    public String toString() {
        // TODO Auto-generated method stub
        return "["+
                "servingSize:"+servingSize+
                ",servings:"+servings+
                ",calories:"+calories+
                ",fat:"+fat+
                ",sodium:"+sodium+
                ",carbohydrate:"+carbohydrate+
                "]";
    }
	
	public static void main(String [] args) {
		NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8)
			.calories(100).sodium(35).carbohydrate(27).build();
		
		System.out.println(cocaCola.toString());
	}
}

출력 결과:
[servingSize:240,servings:8,calories:100,fat:0,sodium:35,carbohydrate:27]
참고:http://www.cnblogs.com/xwdreamer/archive/2012/06/06/2538496.html

좋은 웹페이지 즐겨찾기