Effective Java 1

Item 2 遇到多个构造器参数考虑用构建器Builder

1、什么是构建器?

 1 public class Builder_Pattern {
 2     private final int p1;
 3     private final int p2;
 4     private final int p3;
 5     private final int p4;
 6 
 7     public static class Builder{
 8         private final int p1;
 9         private final int p2;
10 
11         private int p3=0;
12         private int p4=0;
13 
14         public Builder(int p1,int p2){
15             this.p1=p1;
16             this.p2=p2;
17         }
18         public Builder p3(int val){
19             p3=val; return this;
20         }
21         public Builder p4(int val){
22             p4=val; return this;
23         }
24         public Builder_Pattern build(){
25             return new Builder_Pattern(this);
26         }
27     }
28 
29     private Builder_Pattern(Builder builder){
30         p1=builder.p1;p2=builder.p2;p3=builder.p3;p4=builder.p4;
31     }
32 
33 
34 //Builder_Pattern bp=new Builder_Pattern.Builder(1,2).p3(1).p4(1).build(); 注意 p3 p4返回类型是Builder 可以连续调用!
35 }

2、使用构建器的好处。

在多参数时写法优雅,参数具有可读性,保证线程安全,适合类的继承。

3、使用构建器的坏处。

花费会更高,因此在参数有许多的时候建议使用,特别是有很多可选参数时。

猜你喜欢

转载自www.cnblogs.com/WutingjiaWill/p/9139520.html