Builder 模式定义:
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示.
Builder 模式是一步一步创建一个复杂的对象,它允许用户可以只通过指定复杂对象的类型和内容就可以构建它们.用户不知道内部的具体构建细节.Builder 模式是非常类似抽象工厂模式,细微的区别大概只有在反复使用中才能体会到.
为何使用?
是为了将构建复杂对象的过程和它的部件解耦.注意: 是解耦过程和部件.
因为一个复杂的对象,不但有很多大量组成部分,如汽车,有很多部件:车轮 方向盘 发动机还有各种小零件等等,部件很多,但远不止这些,如何将这些部件装配成一辆汽车,这个装配过程也很复杂(需要很好的组装技术),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);
}
}
}
Student并不是直接new出来的,对其构造器进行了处理使其可访问范围尽可能的小,只让它通过Student.Builder来构建自己,在Student.Builder中提供了一种类set的方法链的方式来设置值,然后在最后的build()方法的时候会返回一个Student对象,现在要创建一个Student对象,代码如下:
Student s=new Student.Builder().name("CC").password("qwerty").sex("男").address("银河系第二旋臂").build();
閱讀更多 老孔說編程 的文章