构造方法参数过多该如何解决?-建造者模式

在编码的过程中,不可避免的遇到一个类有很多的成员变量,为了代码的健壮性,大家挖空心思地写各种构造方法,构造方法写到郁闷,貌似还没有全部包含,这个时候推荐大家用建造者模式!以下为具体的实现代码:

public class Goods {
	private final String goodsId;
	private final String goodsName;
	private final String goodsBrand;
	private final String factoryName;
	private final String productionAddress;
	private Double costPrice;
	private Double salePriceLevel1;
	private Double salePriceLevel2;
	private Double salePriceLevel3;
	private Double salePriceLevel4;
	private Double salePriceLevel5;
	private Double salePriceLevel6;
	
	private Goods(GoodsBuilder goodsBuilder){
		this.goodsId = goodsBuilder.goodsId;
		this.goodsName = goodsBuilder.goodsName;
		this.goodsBrand = goodsBuilder.goodsBrand;
		this.factoryName = goodsBuilder.factoryName;
		this.productionAddress = goodsBuilder.productionAddress;
	}
	
	public static class GoodsBuilder{
		private final String goodsId;
		private final String goodsName;
		private final String goodsBrand;
		private final String factoryName;
		private final String productionAddress;
		private Double costPrice;
		private Double salePriceLevel1;
		private Double salePriceLevel2;
		private Double salePriceLevel3;
		private Double salePriceLevel4;
		private Double salePriceLevel5;
		private Double salePriceLevel6;
		
		public GoodsBuilder(String goodsId, String goodsName, String goodsBrand, String factoryName, String productionAddress) {
			super();
			this.goodsId = goodsId;
			this.goodsName = goodsName;
			this.goodsBrand = goodsBrand;
			this.factoryName = factoryName;
			this.productionAddress = productionAddress;
		}
		
		public GoodsBuilder costPrice(Double costPrice){
			this.costPrice = costPrice;
			return this;	
		}
		
		public GoodsBuilder salePriceLevel1(Double salePriceLevel1){
			this.salePriceLevel1 = salePriceLevel1;
			return this;	
		}
		public GoodsBuilder salePriceLevel2(Double salePriceLevel2){
			this.salePriceLevel1 = salePriceLevel1;
			return this;	
		}
		public GoodsBuilder salePriceLevel3(Double salePriceLevel3){
			this.salePriceLevel1 = salePriceLevel1;
			return this;	
		}
		public GoodsBuilder salePriceLevel4(Double salePriceLevel4){
			this.salePriceLevel1 = salePriceLevel1;
			return this;	
		}
		public GoodsBuilder salePriceLevel5(Double salePriceLevel5){
			this.salePriceLevel1 = salePriceLevel1;
			return this;	
		}
		public GoodsBuilder salePriceLevel6(Double salePriceLevel6){
			this.salePriceLevel1 = salePriceLevel1;
			return this;	
		}
		
		public Goods builder(){
			return new Goods(this);
		}
	}
	
	
	public static void main(String[] args) {
		Goods goods = new Goods.GoodsBuilder("goods10001", "apple", "brand1", "factory1", "chengdu")
				.costPrice(1000.0).builder();
  //这里可以根据具体情况调用
	}
	

猜你喜欢

转载自blog.csdn.net/tangtang1226/article/details/81747894