码迷,mamicode.com
首页 > 编程语言 > 详细

java构建器

时间:2019-01-24 20:43:50      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:effect   图片   method   分享   第二版   one   set   str   void   

最近在看“Effective Java 中文第二版”,看到了构建器这个知识,感觉很不错,比挨个调用setter方法看起来简便多了,代码如下:

技术分享图片
 1 public class User {
 2 
 3     private String name;
 4     private int age;
 5     private String sex;
 6     private String number;
 7     private String address;
 8     private int phone;
 9     private String remarks;
10     
11     public static class Builder{
12         private String name;
13         private int age;
14         private String sex;
15         private String number;
16         private String address;
17         private int phone;
18         private String remarks;
19         
20         public Builder(String name){
21             this.name = name;
22         }
23         
24         public Builder age(int val){
25             age = val;
26             return this;
27         }
28         public Builder sex(String val){
29             sex = val;
30             return this;
31         }
32         public Builder number(String val){
33             number = val;
34             return this;
35         }
36         public Builder phone(int val){
37             phone = val;
38             return this;
39         }
40         public Builder remarks(String val){
41             remarks = val;
42             return this;
43         }
44         
45         public User build(){
46             return new User(this);
47         }
48     }
49     
50     public User(Builder builder){
51         name = builder.name;
52         age = builder.age;
53         sex = builder.sex;
54         number = builder.number;
55         address = builder.address;
56         phone = builder.phone;
57         remarks = builder.remarks;
58     }
59 
60     @Override
61     public String toString() {
62         return "User [name=" + name + ", age=" + age + ", sex=" + sex + ", number=" + number + ", address="
63                 + address + ", phone=" + phone + ", remarks=" + remarks + "]";
64     }
65 }
View Code

测试代码

1 public class Test {
2 
3     public static void main(String[] args) {
4         // TODO Auto-generated method stub
5         User user = new User.Builder("zhangsan").age(20).sex("男").build();
6         System.out.println(user.toString());
7     }
8 }
User [name=zhangsan, age=20, sex=男, number=null, address=null, phone=0, remarks=null]

Builder模式十分灵活,可以利用单个 builder构建多个对象。 builder的参数可以在创建对象期间进行调整,也可以随着不同的对象而改变

 

java构建器

标签:effect   图片   method   分享   第二版   one   set   str   void   

原文地址:https://www.cnblogs.com/hushunwei/p/10316579.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!