为什么我可以将 setter 与 class 和内部构建器 class 链接在一起,但不能在普通 class 的实例上链接?

Why can I chain setters with a class with builder class inside but cannot on a instance of a normal class?

我在学习 java 时了解了构建器模式,但我无法理解构建器如何链接 setter 方法。

//this one compiles
new AlertDialog.Builder().setApplyButton("apply").setText("stop");


//this one doesn't compile
new NormalAlert().setApplyButton("apply").setText("stop");

因为在正常的 class setter 中通常 return void 你不能调用另一个类型为 void

的 class setter

构建器模式的简单演示如下所示

public class Alert {
String prop1;
String prop2;
Alert(AlertBuilder builder){
    this.prop1 = builder.prop1;
    this.prop2 = builder.prop2;
}
}
class AlertBuilder{
String prop1;
String prop2;

public AlertBuilder setProp1(String prop1) {
    this.prop1 = prop1;
    return this;
}
public AlertBuilder setProp2(String prop2) {
    this.prop2 = prop2;
    return this;
}
public Alert build(){
    return new Alert(this);
}
}

你有主 class 和建筑 class。构建器模式会不断自我更新,当您准备好构建“真实”对象时,您可以调用构建方法并立即获取所有字段。 如果您有兴趣,我建议您阅读更多有关 Builder 设计模式的内容。

构建器方法return this(构建器实例本身)以便可以在其上调用更多方法。通常,名为build的方法被定义为return构造的对象。

示例:

public class Person {
  private String name;
  private Integer age;

  public static class Builder {
    private String name;
    private Integer age;
        
    public Builder name(String name){
      this.name = name;
      return this;
    }

    public Builder age(Integer age){
      this.age = age;
      return this;
    }

    public Person build() {
        return new Person(this);
    }
  }

  private Person(Builder builder) {
    this.name = builder.name; 
    this.age = builder.age;     
  }
}