-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIterPattern.java
76 lines (58 loc) · 1.6 KB
/
IterPattern.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
65
66
67
68
69
70
71
72
73
74
75
76
package code;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IterPattern {
public static void main(String[] args) {
Cafetaria cafetaria = new Cafetaria();
cafetaria.addMenuItem(new Pizza("Margherita", 5.50));
cafetaria.addMenuItem(new Pizza("Hawaii", 6.50));
cafetaria.addMenuItem(new Pizza("Pepperoni", 7.50));
cafetaria.addMenuItem(new Salad("Caesar", 3.50));
cafetaria.addMenuItem(new Salad("Greek", 4.50));
for (MenuItem menuItem : cafetaria) {
System.out.println(menuItem.getName() + " " + menuItem.getPrice());
}
}
}
class Cafetaria implements Iterable<MenuItem> {
private List<MenuItem> menuItems = new ArrayList<>();
public Iterator<MenuItem> iterator() {
return menuItems.iterator();
}
public void addMenuItem(MenuItem menuItem) {
menuItems.add(menuItem);
}
}
interface MenuItem {
String getName();
double getPrice();
}
class Pizza implements MenuItem {
private String name;
private double price;
public Pizza(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
class Salad implements MenuItem {
private String name;
private double price;
public Salad(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}