Skip to content

Instantly share code, notes, and snippets.

@mankum93
Last active June 22, 2021 02:01
Show Gist options
  • Save mankum93/1074a64049b6452253e148fbeb81fed6 to your computer and use it in GitHub Desktop.
Save mankum93/1074a64049b6452253e148fbeb81fed6 to your computer and use it in GitHub Desktop.
Builder pattern snippet from Effective Java
// Builder pattern for class hierarchies
public abstract class Pizza {
public enum Topping {
HAM,
MUSHROOM,
ONION,
PEPPER,
SAUSAGE
}
final Set < Topping > toppings;
abstract static class Builder < T extends Builder < T >> {
EnumSet < Topping > toppings = EnumSet.noneOf(Topping.class);
public T addTopping(Topping topping) {
toppings.add(Objects.requireNonNull(topping));
return self();
}
abstract Pizza build();
// Subclasses must override this method to return "this"
protected abstract T self();
}
Pizza(Builder < ? > builder) {
toppings = builder.toppings.clone(); // See Item 50
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment