在课堂内外使用构建器模式有什么优势?
课内:
public class Person {
private String name;
private String eyeColor;
private String hairColor;
public Person setName(String name) {
this.name = name;
return this;
}
public Person setEyeColor(String eyeColor) {
this.eyeColor = eyeColor;
return this;
}
public Person setHairColor(String hairColor) {
this.hairColor = hairColor;
return this;
}
}
// Example usage:
Person p = new Person()
.setName("Bob")
.setHairColor("Black")
.setEyeColor("Brown")
课外:
public class Person {
private String name;
private String eyeColor;
private String hairColor;
public Person(String name, String eyeColor, String hairColor) {
this.name = name;
this.eyeColor = eyeColor;
this.hairColor = hairColor;
}
}
public class PersonBuilder {
private String name;
private String eyeColor;
private String hairColor;
public Person build() {
return new Person(name, eyeColor, hairColor);
}
public PersonBuilder with(String name) {
this.name = name;
return this;
}
public PersonBuilder setEyeColor(String eyeColor) {
this.eyeColor = eyeColor;
return this;
}
public PersonBuilder setHairColor(String hairColor) {
this.hairColor = hairColor;
return this;
}
}
// Example usage:
Person p = new PersonBuilder()
.setName("Bob")
.setHairColor("Black")
.setEyeColor("Brown")
.build();