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

posted @ 2018-11-27 21:59  mao2080  阅读(6452)  评论(0编辑  收藏  举报