java builder模式创建对象的使用
转载注明出处 https://www.cnblogs.com/rolayblog/p/10552085.html
背景
由.net转战java,发现在C#语法中,我们新建一个对象赋值时经常这样写:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Person person=new Person(){ 2 age=1, 3 name="Rolay", 4 ...................... 5 }
看起很美观,并且会提示我们哪些赋值了,哪些没有赋值。但是在java中没有看到这样的写法,于是近期的写法全都是这样:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Person person=new Person(); 2 person.age=11; 3 person.name="Rolay'; 4 .................................
这种写法确实也能满足需求,但是属性一旦多了,或者其中有些限制必填或非必填时,很容易看错或者写掉。在读effective java中看到builder模式对于创建对象的使用示例,顺便记录下来别让自己忘了。
正文
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Person { 2 private final String name; 3 private final String gender; 4 private String house; 5 private String age; 6 private String hight; 7 private Integer money; 8 9 public Person(Builder builder) 10 { 11 this.name=builder.name; 12 this.gender=builder.gender; 13 } 14 @Override 15 public String toString() 16 { 17 return "姓名:"+this.name+",性别:"+this.gender; 18 } 19 public static class Builder{ 20 private final String name; 21 private final String gender; 22 private String house; 23 private String age; 24 private String hight; 25 private Integer money; 26 public Builder(String name,String gender){ 27 this.name=name; 28 this.gender=gender; 29 } 30 public Builder house(String house) 31 { 32 this.house=house; 33 return this; 34 } 35 public Builder hight(String hight) 36 { 37 this.hight=hight; 38 return this; 39 } 40 public Builder money(Integer money) 41 { 42 this.money=money; 43 return this; 44 } 45 public Person build() 46 { 47 return new Person(this); 48 } 49 } 50 }
在Person类中定义一个内部类Builder,这个Builder内部类中的属性要和Person中的相同,并且必须有的属性要用final修饰,防止这些属性没有被赋值。然后内部类中定义了一个构造方法,传入必须有的属性。其他非必须的属性都通过方法设置,每个方法都返回Builder对象自身。最后定义了一个build方法,将Builder对象传入Person的私有构造方法,最终返回一个对象。重写toString 返回两个必填项组成的字符串。下面是调用示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Person person=new Person.Builder("张三","男") 2 .hight("1.80").house("big house").money(1000000).build(); 3 System.out.println(person.toString());
甘于平凡,做一个甘于平凡的人,菜米油盐,生老病死。