Advertisement
drSdGdBy

builder pattern for class hierarchies

Mar 18th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.57 KB | None | 0 0
  1. // Builder pattern for class hierarchies
  2. public abstract class Pizza {
  3. public enum Topping { HAM, MUSHROOM, ONION, PEPPER, SAUSAGE }
  4. final Set<Topping> toppings;
  5. abstract static class Builder<T extends Builder<T>> {
  6. EnumSet<Topping> toppings = EnumSet.noneOf(Topping.class);
  7. public T addTopping(Topping topping) {
  8. toppings.add(Objects.requireNonNull(topping));
  9. return self();
  10. }
  11. abstract Pizza build();
  12. // Subclasses must override this method to return "this"
  13. protected abstract T self();
  14. }
  15. Pizza(Builder<?> builder) {
  16. toppings = builder.toppings.clone(); // See Item 50
  17. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement