Builder Pattern – The constructor is private. You create a nested static class called Builder. In the builder you define methods corresponding to the constructor parameters of the nesting class. Each method returns a Builder instance (return this at the end). Drawback is that you duplicate fields in the Builder. Finally you create a method called build in Builder which will call the private constructor of the nesting class and return the newly built nesting class.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package com.vvirlan; public class BuilderExample { public static void main(String[] args) { Pet.Builder builder = new Pet.Builder(); Pet pet = builder.withName("Animal").withKind("Super").withAge(10).build(); System.out.println(pet); } } class Pet { private String name; private String kind; private int age; private Pet(String name, String kind, int age) { this.name = name; this.kind = kind; this.age = age; } public static class Builder { private String name; private String kind; private int age; public Builder withName(String name) { this.name = name; return this; } public Builder withKind(String kind) { this.kind = kind; return this; } public Builder withAge(int age) { this.age = age; return this; } public Pet build() { return new Pet(name, kind, age); } } @Override public String toString() { return "Pet [name=" + name + ", kind=" + kind + ", age=" + age + "]"; } } |