Last active
June 22, 2021 02:01
-
-
Save mankum93/1074a64049b6452253e148fbeb81fed6 to your computer and use it in GitHub Desktop.
Builder pattern snippet from Effective Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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