I try to code a builder pattern for my better understanding. Mostly I relied on GOF and wikipedia. So my Object is a house with required attribute area and some optional attributes (like windows, doors, rooms etc.) I will show you the code. Now, I'm not really sure if its correct and I think I don't have a director? I don't get in which cases you need one and how it works.
This is my class house and the innerclass HouseBuilder
public class House {
//required
private final String area;
//optional
private int windows;
private int doors;
private int rooms;
//constructor with HouseBuilder
private House(HouseBuilder builder) {
this.windows = builder.windows;
this.doors = builder.doors;
this.rooms = builder.rooms;
}
public static class HouseBuilder {
//required
private String area;
//optional
private int windows;
private int doors;
private int rooms;
//constructor with required attributes
HouseBuilder(String area) {
this.area = area;
}
//optional attributes
public HouseBuilder windows(int windows) {
this.windows = windows;
return this;
}
public HouseBuilder doors (int doors) {
this.doors = doors;
return this;
}
//function for building
public Housebuild() {
return new House(this);
}
}
Now, I just got a class demo where I can build a house like that:
House house = new House.HouseBuilder("Downtown") .doors(3).windows(2).build();
But this is not a director like in the books. Is my idea even correct? And why is that better than just using setters?
Thanks!
Aucun commentaire:
Enregistrer un commentaire