Sunday, July 13, 2014

Builder Pattern Snippet

// Ensures members of Cake are immutable. Hence once created it can safely pass between many modules without the risk of being modified.
// It is not completely thread safe on the same builder object, but should suffice most of the cases.
class Cake {
private final String name;
private final int sugar;

public String getName() { return this.name; }
public int getSugar() { return this.sugar; }

private Cake(CakeBuilder builder) { 
this.name = builder.getName();
this.sugar = builder.getSugar();
}

public static class CakeBuilder {
private final String name;  // See how you can make some fields immutable in the builder too.
private int sugar; 

CakeBuilder(String name) {
this.name = name;
}

public String getName() {
return this.name;


public CakeBuilder setSugar(int sugar) {
this.sugar = sugar;
return this;
}

public int getSugar() {
return this.sugar;
}

public Cake build() {
Cake cake = new Cake(this);
return cake;
}
}
}


public static void main (String[] args) throws java.lang.Exception
{
Cake cake = new Cake.CakeBuilder("Vanilla Cake").setSugar(10).build();
}

All credit to the author http://www.javacodegeeks.com/2013/01/the-builder-pattern-in-practice.html