Java中的Builder模式


特別提示:本人博客部分有參考網絡其他博客,但均是本人親手編寫過並驗證通過。如發現博客有錯誤,請及時提出以免誤導其他人,謝謝!歡迎轉載,但記得標明文章出處: http://www.cnblogs.com/mao2080/

1、問題描述

  Java Builder模式主要是用一個內部類去實例化一個對象,避免一個類出現過多構造函數,而且構造函數如果出現默認參數的話,很容易出錯。

2、具體代碼

 1 package com.mao;
 2 
 3 public class User {
 4 
 5     /**賬號*/
 6     private String userName;
 7 
 8     /**密碼*/
 9     private String password;
10 
11     /**年齡*/
12     private int age;
13 
14     /**性別*/
15     private String sex;
16 
17     public String getUserName() {
18         return userName;
19     }
20 
21     public String getPassword() {
22         return password;
23     }
24 
25     public int getAge() {
26         return age;
27     }
28 
29     public String getSex() {
30         return sex;
31     }
32 
33     @Override
34     public String toString() {
35         return "User{" +
36                 "userName='" + userName + '\'' +
37                 ", password='" + password + '\'' +
38                 ", age=" + age +
39                 ", sex='" + sex + '\'' +
40                 '}';
41     }
42 
43     public static class Builder {
44 
45         /**賬號*/
46         private String userName;
47 
48         /**密碼*/
49         private String password;
50 
51         /**年齡*/
52         private int age;
53 
54         /**性別*/
55         private String sex;
56 
57         public Builder userName(String userName) {
58             this.userName = userName;
59             return this;
60         }
61 
62         public Builder password(String password) {
63             this.password = password;
64             return this;
65         }
66 
67         public Builder age(int age) {
68             this.age = age;
69             return this;
70         }
71 
72         public Builder sex(String sex) {
73             this.sex = sex;
74             return this;
75         }
76 
77         public User build() {
78             return new User(this);
79         }
80 
81     }
82 
83     private User(Builder b) {
84         this.age = b.age;
85         this.password = b.password;
86         this.sex = b.sex;
87         this.userName = b.userName;
88     }
89 
90     public static void main(String[] args) {
91         User user = new Builder().age(10).password("abc").sex("男").userName("張三").build();
92         System.out.println(user.toString());
93     }
94 
95 }

3、參考網站

  https://www.cnblogs.com/begin1949/p/4930896.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM