Builder#

Builder pattern is a creational pattern that allows you to create objects step by step.

Builder pattern UML diagram

  • Builder

  • Concrete Builder

  • Director

  • Product

 1public class BuilderPattern {
 2
 3  public static void main(String[] args) {
 4    Modal infoModal = new Modal.Builder()
 5      .setContent("This is simple info modal")
 6      .setConfirmButton("Ok")
 7      .build();
 8
 9    System.out.println(infoModal);
10
11    Modal normalModal = new Modal.Builder()
12      .setHeading("Create User")
13      .setContent("Fields required for creating user")
14      .setConfirmButton("Create User")
15      .setCancelButton("Cancel")
16      .build();
17
18    System.out.println(normalModal);
19  }
20}
21
22class Modal {
23
24  private String heading;
25  private String content;
26  private String confirmButton;
27  private String cancelButton;
28
29  private Modal(
30    String heading,
31    String content,
32    String confirmButton,
33    String cancelButton
34  ) {
35    this.heading = heading;
36    this.content = content;
37    this.confirmButton = confirmButton;
38    this.cancelButton = cancelButton;
39  }
40
41  @Override
42  public String toString() {
43    return String.format(
44      "%s %n %s%n %s    %s",
45      heading,
46      content,
47      confirmButton,
48      cancelButton
49    );
50  }
51
52  static class Builder {
53
54    private String heading;
55    private String content;
56    private String confirmButton;
57    private String cancelButton;
58
59    Builder() {}
60
61    Builder setHeading(String heading) {
62      this.heading = heading;
63      return this;
64    }
65
66    Builder setContent(String content) {
67      this.content = content;
68      return this;
69    }
70
71    Builder setConfirmButton(String confirmButton) {
72      this.confirmButton = confirmButton;
73      return this;
74    }
75
76    Builder setCancelButton(String cancelButton) {
77      this.cancelButton = cancelButton;
78      return this;
79    }
80
81    Modal build() {
82      return new Modal(heading, content, confirmButton, cancelButton);
83    }
84  }
85}