Repository navigation
Expand file tree
/
Copy pathDoubleDispatch.java
More file actions
72 lines (66 loc) · 1.63 KB
/
Copy pathDoubleDispatch.java
File metadata and controls
72 lines (66 loc) · 1.63 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
//: patterns/doubledispatch/DoubleDispatch.java
// Using multiple dispatching to handle more
// than one unknown type during a method call.
package patterns.doubledispatch;
import patterns.trash.*;
import java.util.*;
class AluminumBin extends TypedBin {
@Override
public boolean add(DDAluminum a) {
return addIt(a);
}
}
class PaperBin extends TypedBin {
@Override
public boolean add(DDPaper a) {
return addIt(a);
}
}
class GlassBin extends TypedBin {
@Override
public boolean add(DDGlass a) {
return addIt(a);
}
}
class CardboardBin extends TypedBin {
@Override
public boolean add(DDCardboard a) {
return addIt(a);
}
}
class TrashBinSet {
private TypedBin[] binSet = {
new AluminumBin(),
new PaperBin(),
new GlassBin(),
new CardboardBin()
};
public void sortIntoBins(ArrayList bin) {
Iterator e = bin.iterator();
while(e.hasNext()) {
TypedBinMember t =
(TypedBinMember)e.next();
if(!t.addToBin(binSet))
System.err.println("Couldn't add " + t);
}
}
public TypedBin[] binSet() { return binSet; }
}
public class DoubleDispatch {
public static void main(String[] args) {
ArrayList bin = new ArrayList();
TrashBinSet bins = new TrashBinSet();
// ParseTrash still works, without changes:
ParseTrash.fillBin("DDTrash.dat", bin);
// Sort from the master bin into the
// individually-typed bins:
bins.sortIntoBins(bin);
TypedBin[] tb = bins.binSet();
// Perform sumValue for each bin...
for (TypedBin tb1 : tb) {
Trash.sumValue(tb1.v);
}
// ... and for the master bin
Trash.sumValue(bin);
}
} ///:~