-
Notifications
You must be signed in to change notification settings - Fork 23
/
Menu.java
64 lines (51 loc) · 1.87 KB
/
Menu.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package MenuCompositeWithIterator;
import java.util.ArrayList;
import java.util.Iterator;
public class Menu extends MenuComponent {
// can have any number of children
// we'll use an internal ArrayList to hold these
ArrayList menuComponents = new ArrayList();
String name;
String description;
// we're going to give each Menu a name and a description
public Menu(String name, String description) {
this.name = name;
this.description = description;
}
public void add(MenuComponent menuComponent) {
menuComponents.add(menuComponent);
}
public void remove(MenuComponent menuComponent) {
menuComponents.remove(menuComponent);
}
public MenuComponent getChild(int i) {
return (MenuComponent)menuComponents.get(i);
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
// we aren't overriding getPrice() or isVegetarian() because
// these methods don't make sense for a Menu
public void print() {
System.out.print("\n" + getName());
System.out.println(", " + getDescription());
System.out.println("---------------------");
/* because menu is a composite and contains both
* Menu Items and other Menus,
its print() methods should print everything it contains
*/
Iterator iterator = menuComponents.iterator();
// we use an Iterator to iterate through all the Menu's components
while (iterator.hasNext()) {
MenuComponent menuComponent = (MenuComponent)iterator.next();
menuComponent.print();
}
}
public Iterator createIterator() {
// it knows how to iterate over any composite
return new CompositeIterator(menuComponents.iterator());
}
}