Assign the Builder
class as a static
nested class in the Entity
class. Then the Builder
class can set fields directly, and you donโt need the configuration methods or the n-arg constructor in Entity
.
public class Entity { // Just one attribute and getter here; could be 25. private int data; public int getData() { return data; } public static class Builder { // Just one attribute and getter here; could be 25. private int theData; public Entity build() { Entity entity = new Entity(); // Set private field(s) here. entity.data = theData; return entity; } public Builder setData(int someData) { theData = someData; return this; } } }
Using:
Entity entity = new Entity.Builder().setData(42).build();
source share