设计模式之-【Builder模式】

public class Main5{
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 sodium = 0;
		
		private int carbohydrate = 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 fat(int fat){
			this.fat = fat;
			return this;
		}
		
		public Builder sodium(int sodium){
			this.sodium = sodium;
			return this;
		}
		
		public Builder carbohydrate(int carbohydrate){
			this.carbohydrate = carbohydrate;
			return this;
		}
		
		public Main5 build(){
			return new Main5(this);
		}
	}
	
	private Main5(Builder builder){
		servingSize = builder.servingSize;
		servings = builder.servings;
		calories = builder.calories;
		fat = builder.fat;
		sodium = builder.sodium;
		carbohydrate = builder.carbohydrate;
	}
}

 

当一个类有很多属性

有很多的熟悉可以是默认的值的时候

可以通过写多个不同参数的构造方法去实现

但是很麻烦

这种方式设计上很灵活

基本上可以上任意的组合见Effective java (中文第二版) 第11页

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