Builder Pattern
- Separate the construction of a complex object from its representation so that the same construction process can create different representations.
- ref: https://java-design-patterns.com/patterns/builder/#explanation
- Helps in avoiding long constructors (telescoping constructors) with lots of params
- Object created at the end is immutable
- Class & Builder
public final class Hero {
private final String name;
private final HairColor hairColor;
private final Weapon weapon;
private Hero(Builder builder) {
this.name = builder.name;
this.hairColor = builder.hairColor;
this.weapon = builder.weapon;
}
public static class Builder {
private final String name;
private HairColor hairColor;
private Weapon weapon;
public Builder(String name) {
if (name == null) {
throw new IllegalArgumentException("name can not be null");
}
this.name = name;
}
public Builder withHairColor(HairColor hairColor) {
this.hairColor = hairColor;
return this;
}
public Builder withWeapon(Weapon weapon) {
this.weapon = weapon;
return this;
}
public Hero build() {
return new Hero(this);
}
}
}
var mage = new Hero.Builder("Riobard")
.withHairColor(HairColor.BLACK)
.withWeapon(Weapon.DAGGER)
.build();
StringBuilder
String does not allow appending because String is immutable
- Each method you invoke on
String creates a new object and returns it
StringBuilder is mutable and can concatenate strings
toString() finally generate an immutable String
StringBuilder sb = new StringBuilder();
sb.append("hello");
sb.append(" world");
sb.toString();
Fluent Builder Pattern
- This pattern forces the user to set the attributes in a particular order
- example: Stream API, Mockito