建造者设计模式的功能:用来创建对象的
实现public class Dept {
private Integer deptno;
private String dname;
private String loc;
//步骤5:实体类提供全参构造方法
private Dept(Integer deptno, String dname, String loc) {
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
@Override
public String toString() { // 为了方便查看输出结果
return "Dept{" +
"deptno=" + deptno +
", dname='" + dname + '\'' +
", loc='" + loc + '\'' +
'}';
}
public static DeptBuilder newBuilder() { //步骤 2:提供返回Builder的静态方法
return new DeptBuilder();
}
public static class DeptBuilder { //步骤 1:定义Builder类
//步骤3:提供和实体类一样的属性
private Integer deptno;
private String dname;
private String loc;
//步骤4:提供设置属性的方法
public DeptBuilder deptno(Integer deptno) {
this.deptno = deptno;
return this;
}
public DeptBuilder dname(String dname) {
this.dname = dname;
return this;
}
public DeptBuilder loc(String loc) {
this.loc = loc;
return this;
}
public Dept build(){ //步骤6:提供返回实体类的方法
return new Dept(deptno,dname,loc);
}
}
}
测试代码:
public static void main(String[] args) {
Dept dept2= Dept.builder()
.deptno(20)
.dname("RESEARCH")
.loc("DALLAS")
.build();
System.out.println(dept2);
}
Lombok版
- 原代码:
@Builder
public class Dept {
private Integer deptno;
private String dname;
private String loc;
}
- 编译后生成的代码:
public class Dept {
private Integer deptno;
private String dname;
private String loc;
Dept(Integer deptno, String dname, String loc) {
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
public static DeptBuilder builder() {
return new DeptBuilder();
}
public static class DeptBuilder {
private Integer deptno;
private String dname;
private String loc;
public DeptBuilder deptno(Integer deptno) {
this.deptno = deptno;
return this;
}
public DeptBuilder dname(String dname) {
this.dname = dname;
return this;
}
public DeptBuilder loc(String loc) {
this.loc = loc;
return this;
}
public Dept build() {
return new Dept(this.deptno, this.dname, this.loc);
}
public String toString() {
return "Dept.DeptBuilder(deptno=" + this.deptno + ", dname=" + this.dname + ", loc=" + this.loc + ")";
}
}
}
示例:自定义Map工具类(重点)
public class MapUtil{
public static MapBuilder builder() {
return new MapBuilder(new HashMap());
}
public static class MapBuilder {
private final Map map ;
public MapBuilder(Map map) {
this.map = map;
}
public MapBuilder put(K k, V v) {
map.put(k, v);
return this;
}
public Map build() {
return map;
}
}
public static void main(String[] args) {
Map map = MapUtil.builder().put("a", "aaaa").put("b", 1111).build();
map.forEach((k, v) -> System.out.println(k + " : " + v));
}
}