When you have Builder
to create a model object, the build()
method is responsible for the creation of this object, in many examples and materials I have seen this creation done in two ways:
public final class Cidade {
private Integer id;
private Integer codigo;
private String descricao;
private Cidade(final Integer codigo, final String descricao) {
this.codigo = codigo;
this.descricao = descricao;
}
public Integer getId() {
return id;
}
public Integer getCodigo() {
return codigo;
}
public String getDescricao() {
return descricao;
}
public static class Builder {
private Integer codigo;
private String descricao;
public static Builder create() {
return new Builder();
}
public Builder codigo(final Integer codigo) {
this.codigo = codigo;
return this;
}
public Builder descricao(final String descricao) {
this.descricao = descricao;
return this;
}
public Cidade build() {
return new Cidade(this.codigo, this.descricao);
}
}
}
builder
itself as a parameter and from it are fed the properties in the constructor.
public final class Cidade {
private Integer id;
private Integer codigo;
private String descricao;
private Cidade(final Builder builder) {
this.codigo = builder.codigo;
this.descricao = builder.descricao;
}
public Integer getId() {
return id;
}
public Integer getCodigo() {
return codigo;
}
public String getDescricao() {
return descricao;
}
public static class Builder {
private Integer codigo;
private String descricao;
public static Builder create() {
return new Builder();
}
public Builder codigo(final Integer codigo) {
this.codigo = codigo;
return this;
}
public Builder descricao(final String descricao) {
this.descricao = descricao;
return this;
}
public Cidade build() {
return new Cidade(this);
}
}
}
For me it is not clear and I would like to know when to use the constructor of the model object based on a Builder instead of passing parameters to it?