-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIteratorTest.java
More file actions
139 lines (110 loc) · 2.48 KB
/
IteratorTest.java
File metadata and controls
139 lines (110 loc) · 2.48 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/*
A Behavioral Pattern.
Provide a way to access the elements of an aggregate object
sequentially without exposing its underlying representation.
*/
import java.util.ArrayList;
public class IteratorTest {
public static void main(String[] args){
System.out.println("-------------- ITERATOR ---------------");
Container container = new Cart();
container.add(new Item("HarryPotter I", 100.00));
container.add(new Item("Gupi Gyne Bagha Byne", 110.90));
container.add(new Item("KhaaiKhaai", 12.82));
container.add(new Item("UML User Guide", 78.87));
container.add(new Item("Mastering EJB", 75.80));
Iterator iter = container.getIterator();
for (Item item = iter.first(); iter.hasMore(); item = iter.next())
{
System.out.println(item.getName()+" at "+item.getPrice());
}
}
}
// Item
class Item {
String name;
double price;
Item(String nm, double prc){
name = nm;
price = prc;
}
public void setName(String nm){
}
public String getName(){
return name;
}
public void setPrice(double prc){
price = prc;
}
public double getPrice(){
return price;
}
};
// Abstract Aggregate
interface Container {
public void add(Item i);
public Item get(int i);
public void remove(int i);
public int size();
public Iterator getIterator();
};
// Abstract Iterator
interface Iterator {
public Item first();
public Item current();
public Item next();
public Item last();
public boolean hasMore();
};
// Concrete Aggregate
class Cart implements Container {
ArrayList list = null;
Cart(){
list = new ArrayList();
}
public void add(Item i){
list.add(i);
}
public Item get(int i){
return (Item)list.get(i);
}
public void remove(int i){
list.remove(i);
}
public int size(){
return list.size();
}
public Iterator getIterator(){
return new ItemCollector(this);
}
};
// Concrete Iterator
class ItemCollector implements Iterator {
Container container = null;
int current = 0;
ItemCollector(Container cont){
container = cont;
}
public Item first(){
return container.get(0);
}
public Item current(){
return container.get(current);
}
public Item last(){
return container.get(container.size()-1);
}
public Item next(){
current++;
if(hasMore()){
return current();
}
return null;
}
public boolean hasMore(){
if(current >= container.size()){
return false;
}
return true;
}
};