最近在看“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 }
测试代码
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的参数可以在创建对象期间进行调整,也可以随着不同的对象而改变
原文地址:https://www.cnblogs.com/hushunwei/p/10316579.html
时间: 2024-10-07 16:05:02