程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> 遇到多個構造器參數時要考慮用構造器,參數構造

遇到多個構造器參數時要考慮用構造器,參數構造

編輯:JAVA綜合教程

遇到多個構造器參數時要考慮用構造器,參數構造


一般的重疊構造器模式:

 

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);
     }
      
   }

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved