Just getting my head around the Builder pattern and I have a few (noob) questions. Mainly, why can't we just simplify the creation of a builder object?
Instead of this:
public final class Person{
private final String name;
private final String description;
private Person(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public static class Builder {
private String name;
private String description;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setDescription(String description) {
this.description = description;
return this;
}
public Person build() {
return new Person(name, description);
}
}
}
//Use it
Person p = new Person.Builder().setName("test").setDescription("description").build();
Why not just use this?
public final class Person {
private String name;
private String description;
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Person setName(String name){
this.name=name;
return this;
}
public Person setDescription(String description){
this.description=description;
return this;
}
}
//Use it
Person p = new Person().setName("test").set("description");
I see maybe the first one is used when you want to build an immutable object, but other than that why can't I just use the second one instead? It's far simpler. Please provide examples as much as possible.
Aucun commentaire:
Enregistrer un commentaire