定义:
建造者模式:是将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
如果一个对象的属性比较多比较复杂,那么在创建的时候,我们可以采用建造者来灵活地建造,使我们程序更加优雅
public class Person {
private String name; //名字
private int age; //年龄
private double height; //身高
private double weight; //体重
public Person(){
super();
}
public Person(Builder builder){
this.name = builder.name;
this.age = builder.age;
this.height = builder.height;
this.weight = builder.weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public static class Builder{
public String name; //名字
public int age; //年龄
public double height; //身高
public double weight; //体重
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Builder setHeight(double height) {
this.height = height;
return this;
}
public Builder setWeight(double weight) {
this.weight = weight;
return this;
}
public Person build(){
Person person = new Person(this);
return person;
}
}
}
调用方式
Person.Builder builder = new Person.Builder();
Person person = builder.setName("android工程师")
.setAge(29)
.setHeight(176)
.setWeight(135)
.build();
网友评论