简述
Builder模式可以将一个类的构建和表示进行分离。
例子
http://www.cnblogs.com/cc11001100/p/5939220.html
* 使用 builder 模式
public class Student {
private int id;
private String name;
private String passwd;
private String sex;
private String address;
// 构造器尽量缩小范围
private Student() {
}
// 构造器尽量缩小范围
private Student(Student origin) {
// 拷贝一份
this.id = origin.id;
this.name = origin.name;
this.passwd = origin.passwd;
this.sex = origin.sex;
this.address = origin.address;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getPasswd() {
return passwd;
}
public String getSex() {
return sex;
}
public String getAddress() {
return address;
}
/**
* Student的创建完全依靠Student.Builder,使用一种方法链的方式来创建
*
*/
public static class Builder {
private Student target;
public Builder() {
target = new Student();
}
public Builder address(int id) {
target.id = id;
return this;
}
public Builder name(String name) {
target.name = name;
return this;
}
public Builder password(String passwd) {
target.passwd = passwd;
return this;
}
public Builder sex(String sex) {
target.sex = sex;
return this;
}
public Builder address(String address) {
target.address = address;
return this;
}
public Student build() {
return new Student(target);
}
}
}
-
不使用 builder 模式
public class Student { private int id; private String name; private String passwd; private String sex; private String address; public Student() { } public Student(String name, String passwd, String sex, String address) { super(); this.name = name; this.passwd = passwd; this.sex = sex; this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
那么,使用 builder 模式在创建对象的时候,使用
Student s = newStudent.Builder().name("CC").password("qwerty").sex("男").address("xxx").build();
的方式可以创建,通过 builder 这个内部类的方法来规定参数的值,并且最后返回一个这样的对象,优点是参数内容清晰。而一般的创建对象时嗲用 set 方法的方式参数意义很难表达。
(后面可以多个方法列举的原因是每个方法都返回了一个 builder 对象)
网友评论