传统的javaBean
/**
* @ClassName MyObject
* @Description
* @author Cheng.Wei
* @date 2018年1月29日 下午9:16:34
*
*/
public class MyObject {
private Integer age;
private Float height;
private Float weight;
private Boolean house;
private Boolean car;
/**
* @param age
* @param height
* @param weight
* @param house
* @param car
*/
public MyObject(Integer age, Float height, Float weight, Boolean house, Boolean car) {
super();
this.age = age;
this.height = height;
this.weight = weight;
this.house = house;
this.car = car;
}
/**
* @return the age
*/
public Integer getAge() {
return age;
}
/**
* @param age
* the age to set
*/
public void setAge(Integer age) {
this.age = age;
}
/**
* @return the height
*/
public Float getHeight() {
return height;
}
/**
* @param height
* the height to set
*/
public void setHeight(Float height) {
this.height = height;
}
/**
* @return the weight
*/
public Float getWeight() {
return weight;
}
/**
* @param weight
* the weight to set
*/
public void setWeight(Float weight) {
this.weight = weight;
}
/**
* @return the house
*/
public Boolean getHouse() {
return house;
}
/**
* @param house
* the house to set
*/
public void setHouse(Boolean house) {
this.house = house;
}
/**
* @return the car
*/
public Boolean getCar() {
return car;
}
/**
* @param car
* the car to set
*/
public void setCar(Boolean car) {
this.car = car;
}
@Override
public String toString() {
return "MyObject [age=" + age + ", height=" + height + ", weight=" + weight + ", house=" + house + ", car="
+ car + "]";
}
}
传统方式或是通过 set方式赋值、或是通过构造方法
说说set方式:直观 、但对复杂对象的支持不够友好,一排排set方法确实不够优雅。
构造方法:一个方法就能搞定、缺点也相当的明显,少数属性赋值时,不够友好且无法从方法调用方中直观感知所传参数的实际意义,若是构造多个方法,则显得javeBean臃肿,难以实现灵活装配。
============================================================================
我们经常看到链式结构的对象调用,写法极其优雅,兼具了set和构造方法的优点,即可让阅读者感知实际参数的意义又可根据需要自由装配。
/**
* @ClassName Builder
* @Description Builds
* @author Cheng.Wei
* @date 2018年1月29日 下午9:21:27
*
*/
public class Builder {
private Integer age;
private Float height;
private Float weight;
private Boolean house;
private Boolean car;
public MyObject build() {
return new MyObject(age, height, weight, house, car);
}
public Builder age(Integer age) {
this.age = age;
return this;
}
public Builder height(Float height) {
this.height = height;
return this;
}
public Builder weight(Float weight) {
this.weight = weight;
return this;
}
public Builder house(Boolean house) {
this.house = house;
return this;
}
public Builder car(Boolean car) {
this.car = car;
return this;
}
}
调用