gpt4 book ai didi

java - 构建器模式(java)。为什么 Builder 类是公共(public)的?

转载 作者:行者123 更新时间:2023-12-01 18:17:32 25 4
gpt4 key购买 nike

为什么我每次看到内部构建器类都是公共(public)静态的?不应该是私有(private)静态吗?也许我没有看到什么,但我会说它会更好。谁能给我解释一下吗?

@Getter @AllArgsConstructor @ToString
public class CarDto {

private final String make;
private final int seatCount;
private final String type;
private final CarDto carDto;

public static Builder builder(){
return new Builder();
}


private static class Builder{
private String make;
private int seatCount;
private String type;
private CarDto carDto;


public Builder make(String make){
this.make = make;
return this;
}

public Builder seatCount(int seatCount){
this.seatCount = seatCount;
return this;
}

public Builder type(String type){
this.type = type;
return this;
}

public Builder carDto(CarDto carDto){
this.carDto = carDto;
return this;
}

public CarDto create(){
return new CarDto(make, seatCount,type,carDto);
}
}
}

最佳答案

Builder 必须是公共(public)的才能从其他类访问。尝试获取构建器,调用静态工厂方法 CarDto.builder() 否则 - 您将无法使用任何构建方法,例如 seatCount(), 。 .., create().

关于java - 构建器模式(java)。为什么 Builder 类是公共(public)的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60339124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com