As you create a java class, you also define a static builder class, which holds the exact same fields as your original Java class.
For each field in the builder class, define a setter-method that sets the value specified on correct field, and return the it self (the builder object).
At the end you define a build-method that returns a new instance of the original class.
class Fudge { private final int condensedMilk; private final String chocolateType; public static class Builder { //exact same fields as in the original class private int condensedMilk; private String chocolateType; //Our setter-methods, which returns it self (the builder object) public Builder condensedMilk(int can){this.condensedMilk = can; return this; } public Builder chocolateType(String type){this.chocolateType = type; return this; } public Fudge build() { System.out.println("Fudge created!"); return new Fudge(this); } } //A private constructor for the Fudge class //Having this constructor as private make sure that you can't //instance this class in any other way than through the builder class private Fudge(Builder builder) { this.condensedMilk = builder.condensedMilk; this.chocolateType = builder.chocolateType; } } public class BuilderPatternExample { public static void main(String args[]) { //Create a new fudge with white chocolate Fudge WhiteChocolateFudge = new Fudge.Builder() .condensedMilk(1) .chocolateType("White") .build(); } }
Enjoy!
Inga kommentarer:
Skicka en kommentar