Builder pattern: build a house : Builder Pattern « Design Pattern « Java Tutorial






import java.util.LinkedList;
import java.util.List;

public class BuilderDemo {

  public static void main(String[] args) {
    HouseBuilder builder = new SimpleHouseBuilder();
    HouseBuildingCompany houseBuildingCompany = new HouseBuildingCompany();
    House house = houseBuildingCompany.build(builder);
    System.out.println(house);
  }

}

interface HouseBuilder {

  void buildBasement();

  void buildWalls();

  void buildRoof();

  House getHouse();

}

class HouseBuildingCompany {

  public House build(HouseBuilder builder) {
    builder.buildBasement();
    builder.buildWalls();
    builder.buildRoof();
    return builder.getHouse();
  }

}

class SimpleHouseBuilder implements HouseBuilder {
  private House house;

  public SimpleHouseBuilder() {
    this.house = new House();
  }

  public void buildBasement() {
    this.house.setBasement(new Basement());
  }

  public void buildWalls() {
    for (int i = 0; i < 4; i++)
      this.house.addWall(new Wall());
  }

  public void buildRoof() {
    this.house.setRoot(new Roof());
  }

  public House getHouse() {
    return this.house;
  }
}

class Basement {
  @Override
  public String toString() {
    return "Basement";
  }
}

class Wall {
  @Override
  public String toString() {
    return "Wall";
  }
}

class Roof {
  @Override
  public String toString() {
    return "Roof";
  }
}

class House {
  private Basement basement;

  private List<Wall> walls;

  private Roof roof;

  public House() {
    this.walls = new LinkedList<Wall>();
  }

  public void addWall(Wall wall) {
    this.walls.add(wall);
  }

  public void setRoot(Roof roof) {
    this.roof = roof;
  }

  public void setBasement(Basement basement) {
    this.basement = basement;
  }

  @Override
  public String toString() {
    return "House {" + this.basement + ", " + this.walls + ", " + this.roof + "}";
  }
}








34.6.Builder Pattern
34.6.1.Example of the Builder pattern
34.6.2.Builder pattern with interface
34.6.3.Builder pattern: build a house