构建复杂对象
代码结构
源码
package com.myspringboot.shejimoshi.goujianzhe;
public class Main {
public static void main(String[] args) {
Person person = Person.asBuilder()
.basicInfo(1, "zhangsan", 18)
.score(20)
.weight(120)
.loc("bj", "23")
.build();
System.out.println(person);
}
}
package com.myspringboot.shejimoshi.goujianzhe;
public class Person {
int id;
String name;
int age;
double weight;
int score;
Location loc;
private Person() {
}
public static PersonBuilder asBuilder() {
return new PersonBuilder();
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", weight=" + weight +
", score=" + score +
", loc=" + loc +
'}';
}
public static class PersonBuilder {
Person p = new Person();
public PersonBuilder basicInfo(int id, String name, int age) {
p.id = id;
p.name = name;
p.age = age;
return this;
}
public PersonBuilder weight(double weight) {
p.weight = weight;
return this;
}
public PersonBuilder score(int score) {
p.score = score;
return this;
}
public PersonBuilder loc(String street, String roomNo) {
p.loc = new Location(street, roomNo);
return this;
}
public Person build() {
return p;
}
}
}
class Location {
String street;
String roomNo;
public Location(String street, String roomNo) {
this.street = street;
this.roomNo = roomNo;
}
@Override
public String toString() {
return "Location{" +
"street='" + street + '\'' +
", roomNo='" + roomNo + '\'' +
'}';
}
}