优雅的构造器模式
1 public class A { 2 3 private int a; 4 5 private int b; 6 7 private int c; 8 9 10 11 public int getA() { 12 return a; 13 } 14 public int getB() { 15 return b; 16 } 17 public int getC() { 18 return c; 19 } 20 public static class Builder { 21 22 private int a; 23 24 private int b; 25 26 private int c; 27 28 public Builder(){} 29 30 public Builder seta(int a) { this.a = a; return this;} 31 32 public Builder setb(int b) { this.b = b; return this;} 33 34 public Builder setc(int c) { this.c = c; return this;} 35 36 public A build() { return new A(this);} 37 38 } 39 40 41 42 private A(Builder builder) { 43 44 this.a = builder.a; 45 46 this.b = builder.b; 47 48 this.c = builder.c; 49 50 } 51 public static void main(String[] args) { 52 A a = new A.Builder().seta(0).setb(1).setc(2).build(); 53 System.out.println(a.getA()+a.getB()+a.getC()); 54 } 55 56 }
输出 : 3