一、使用场景
一般用于复杂对象的创建,比直接通过有参构造器好,好在哪里暂时不知道
二、实体类
手动写
public class Phone {
private String cpu;
private String screen;
private String memory;
private String mainboard;
private Phone(Builder builder){
this.cpu = builder.cpu;
this.screen = builder.screen;
this.memory = builder.memory;
this.mainboard = builder.mainboard;
}
public static final class Builder{
private String cpu;
private String screen;
private String memory;
private String mainboard;
public Builder cpu(String cpu){
this.cpu = cpu;
return this;
}
//使用构建者创建phone对像
public Phone build(){
return new Phone(this);
}
}
通过lombok插件
@Data
@Builder
@ToString
public class Phone {
private String cpu;
private String screen;
private String memory;
private String mainboard;
}
三、使用方法
public class Client {
public static void main(String[] args) {
//通过构建者对象获取手机对象
Phone phone = Phone.builder()
.cpu("amd")
.memory("扎实吨")
.screen("三闸")
.mainboard("大人硕")
.build();
System.out.println(phone);
}
}
-------------------------------------------------------------------
Phone(cpu=amd, screen=三闸, memory=扎实吨, mainboard=大人硕)