有时候我们要经常给一个类去赋值,但是参数过多时,记不清楚参数和属性的对应了,所以我们就引入Build设计模式了。接下来我用一个类来简单模拟一个Build设计模式。
public class User {
private String name;
private String sex;
private User() {
}
private User(User user) {
this.name = user.name;
this.sex = user.sex;
}
public String getName(){
return name;
}
public String getSex(){
return sex;
}
public static class Builder{
private User user;
public Builder() {
user=new User();
}
public Builder setName(String name){
user.name=name;
return this;
}
public Builder setSex(String sex){
user.sex=sex;
return this;
}
public User build(){
return new User(user);
}
}
}