/**
* 使用builder模式构建people
*/
public class People{
String id;
String name;
int age;
Shape shape;
public static class PeopleBuilder{
People people = new People();
public PeopleBuilder baseInfo(String id, String name){
people.id = id;
people.name = name;
return this;
}
public PeopleBuilder ageInfo(int age){
people.age = age;
return this;
}
public PeopleBuilder shapeInfo(int height, int weight){
people.shape = new Shape(height, weight);
return this;
}
public People builder(){
return people;
}
}
}
class Shape{
int height;
int weight;
public Shape(int height, int weight) {
this.height = height;
this.weight = weight;
}
}
class Test{
public static void main(String[] args) {
People.PeopleBuilder peopleBuilder = new People.PeopleBuilder();
People zhangsan = peopleBuilder.baseInfo("1", "zhangsan").ageInfo(18).shapeInfo(180, 120).builder();
System.out.println(zhangsan.id + "," + zhangsan.name + "," + zhangsan.age + "," + zhangsan.shape.height + "," + zhangsan.shape.weight);
}
}
结果:
1,zhangsan,18,180,120