1 public class Phone { 2 3 private String cpu; 4 private String screen; 5 private String memory; 6 private String mainboard; 7 8 //私有构造方法 9 private Phone(Builder builder) { 10 this.cpu = builder.cpu; 11 this.screen = builder.screen; 12 this.memory = builder.memory; 13 this.mainboard = builder.mainboard; 14 } 15 16 @Override 17 public String toString() { 18 return "Phone{" + 19 "cpu='" + cpu + '\'' + 20 ", screen='" + screen + '\'' + 21 ", memory='" + memory + '\'' + 22 ", mainboard='" + mainboard + '\'' + 23 '}'; 24 } 25 26 public static final class Builder { 27 private String cpu; 28 private String screen; 29 private String memory; 30 private String mainboard; 31 32 public Builder cpu(String cpu) { 33 this.cpu = cpu; 34 return this; 35 } 36 37 public Builder screen(String screen) { 38 this.screen = screen; 39 return this; 40 } 41 public Builder memory(String memory) { 42 this.memory = memory; 43 return this; 44 } 45 public Builder mainboard(String mainboard) { 46 this.mainboard = mainboard; 47 return this; 48 } 49 50 //使用构建者创建Phone对象 51 public Phone build() { 52 return new Phone(this); 53 } 54 } 55 }
public class Client { public static void main(String[] args) { //创建手机对象 通过构建者对象获取手机对象 Phone phone = new Phone.Builder() .cpu("intel") .screen("三星屏幕") .memory("金士顿内存条") .mainboard("华硕主板") .build(); System.out.println(phone); } }