问题: 对于多个构造器参数问题,部分field是必须的,部分field是可选的,如何构造类?
1. 重叠构造器
提供一个参数为必须field的构造器, 然后提供一系列可选参数逐渐递增的构造器
缺点: 构造器参数很多的时候,会失去控制
2. JavaBeans模式
不提供有参数的构造器,对于field,只通过setter()设置。
缺点: 对象状态是可变的,可以随时通过setter()改变对象field的状态,不可控
3. Build模式
示例:
public class Blog {
private final String title;
private final String abstract;
private final String content;
private final String optional1;
private final String optional2;
private Blog (Build build) {
title = build.title;
abstract = build.abstract;
content = build.content;
optional1 = build.optional1;
optional2 = build.optional2;
}
public static class Builder {
private final String title;
private final String abstract;
private final String content;
private final String optional1;
private final String optional2;
public Builder(String title, String abstract, String content) {
this.title = title;
this.abstract = abstract;
this.content = content;
}
public Builder optional1 (String optional1) {
this.optional1 = optional1;
}
public Builder optional2 (String optional2) {
this.optional2 = optional2;
}
public Blog build() {
return new Blog(this);
}
}
}
class Client {
public static void main (String[] args) {
Blog blog = newBlog.Builder("title", "abstract", "content").optional1("optional1").optional2("optional2").build();
}
}
优点:清晰易懂,对象构造出来后,状态不可变,易控制。