69 lines
1.6 KiB
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: 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) {
2015-05-27 23:30:19 -07:00
for(Object aBin : bin) {
TypedBinMember t = (TypedBinMember)aBin;
2015-05-05 11:20:13 -07:00
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) {
2015-05-27 23:30:19 -07:00
ArrayList<Trash> bin = new ArrayList<>();
2015-05-05 11:20:13 -07:00
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);
// Perform sumValue for each bin...
2015-05-27 23:30:19 -07:00
for(TypedBin tb1 : bins.binSet())
2015-05-05 14:05:39 -07:00
Trash.sumValue(tb1.v);
2015-05-05 11:20:13 -07:00
// ... and for the master bin
Trash.sumValue(bin);
}
} ///:~