-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathPizza.java
33 lines (26 loc) · 1018 Bytes
/
Pizza.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package effectivejava.chapter2.item2.hierarchicalbuilder;
import java.util.*;
// Builder pattern for class hierarchies (Page 14)
// Note that the underlying "simulated self-type" idiom allows for arbitrary fluid hierarchies, not just builders
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();
@SuppressWarnings("unchecked")
protected T self() {
// this is always of type T
// so there is no need to override
// self in subclasses
return (T) this;
}
}
Pizza(Builder<?> builder) {
toppings = builder.toppings.clone(); // See Item 50
}
}