簡單的builder構造器示列

Java代碼  收藏代碼

  1. /** 

  2.  * Created by baixiaobin  

  3.  */  

  4. public class User {  

  5.   

  6.     private final int id;  

  7.   

  8.     private final String name;  

  9.   

  10.     private final String sex;  

  11.   

  12.     private final String des;  

  13.   

  14.     public int getId() {  

  15.         return id;  

  16.     }  

  17.   

  18.     public String getName() {  

  19.         return name;  

  20.     }  

  21.   

  22.     public String getSex() {  

  23.         return sex;  

  24.     }  

  25.   

  26.     public String getDes() {  

  27.         return des;  

  28.     }  

  29.   

  30.     public static class Builder {  

  31.   

  32.         private final int id;  

  33.         private final String name;  

  34.   

  35.         private String sex;  

  36.   

  37.         private String des;  

  38.   

  39.         public User build() {  下載 

  40.             return new User(this);  

  41.         }  

  42.   

  43.         /** 

  44.          * id   主鍵id 

  45.          *  name 名稱 

  46.          */  

  47.         public Builder(int id, String name) {  

  48.             this.id = id;  

  49.             this.name = name;  

  50.         }  

  51.   

  52.         public Builder sex(String sex) {  

  53.             this.sex = sex;  

  54.             return this;  

  55.         }  

  56.   

  57.         public Builder des(String des) {  

  58.             this.des = des;  

  59.             return this;  

  60.         }  

  61.   

  62.     }  

  63.   

  64.     private User(Builder builder) {  

  65.         this.id = builder.id;  

  66.         this.name = builder.name;  

  67.         this.des = builder.des;  

  68.         this.sex = builder.sex;  

  69.     }  

  70.   

  71. }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章