首页 > 其他 > 详细

遇到多个构造器参数时要考虑用构造器

时间:2016-02-18 11:52:26      阅读:195      评论:0      收藏:0      [点我收藏+]

一般的重叠构造器模式:

 

public class NutritionFacts{
   private final int one;
   private final int two;
   private final int three;
   public NutritionFacts(int one,int two,int three){
     this.one = one;
     this.two = two;
     
   
   }
   public NutritionFacts(int one){
     this(one,0);
   }
   public NutritionFacts(int one,int two){
     this(one,two,0);
   }

}

//调用的时候 NutritionFacts nt = new NutritionFacts(0,0,0);
//缺点 :重叠构造器模式,有许多参数的时候,难编写和阅读;

改进:Builder模式:

public class NutritionFacts{
   private final int one;
   private final int two;
   private final int three;
   
   private NutritionFacts(Bulider builder){
      one = builder.one;
      two = builder.two;
      three = builder.three;
   }
   
   public static class Builder{
     private  String name;
     private  int one = 0;
     private  int two = 0 ;
     private  int three = 0;
     public Builder(String name){
       this.name = name;
     }
     public Builder one(int value){
         one = value; 
         reture this;
     }
      public Builder two(int value){
         two = value; 
         reture this;
     }
      public Builder two(int value){
         two = value; 
         reture this;
     }
     //调用的时候,最后实例化外部类
     public NutritionFacts build(){
       return new NutritionFacts(this);
     }
      
   }

}

遇到多个构造器参数时要考虑用构造器

原文:http://www.cnblogs.com/520-1314/p/5197420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!