我正在阅读Josh Bloch的书" Effective Java",他建议在构建具有大量成员的对象时使用构建器设计模式.从我所看到的不是香草的设计模式,而是看起来像他的变化.我更喜欢它的外观,并试图在我正在编写的C#Web应用程序中使用它.这是用Java编写的代码并且工作得很好
public class Property {
private String title;
private String area;
private int sleeps = 0;
public static void main(String[] args) {
Property newProperty = new Property.Builder("Test Property").Area("Test Area").Sleeps(7).build();
}
private Property(Builder builder) {
this.title = builder.title;
this.area = builder.area;
this.sleeps =builder.sleeps;
}
public static class Builder{
private String title;
private String area;
private int sleeps = 0;
public Builder (String title){
this.title = title;
}
public Builder Area(String area){
this.area = area;
return this;
} …Run Code Online (Sandbox Code Playgroud)