16.5 抽象的应用
16.5 抽象的应用
走到这一步,接下来该考虑一下设计方案剩下的部分了——在哪里使用类?既然归类到垃圾箱的办法非常不雅且过于暴露,为什么不隔离那个过程,把它隐藏到一个类里呢?这就是著名的“如果必须做不雅的事情,至少应将其本地化到一个类里”规则。看起来就象下面这样:

现在,只要一种新类型的
class TrashSorter extends Vector {
void sort(Trash t) { /* ... */ }
}
也就是说,
TrashSorter ts = new TrashSorter();
ts.addElement(new Vector());
但是现在,

其中,
用于
//: RecycleB.java
// Adding more objects to the recycling problem
package c16.recycleb;
import c16.trash.*;
import java.util.*;
// A vector that admits only the right type:
class Tbin extends Vector {
Class binType;
Tbin(Class binType) {
this.binType = binType;
}
boolean grab(Trash t) {
// Comparing class types:
if(t.getClass().equals(binType)) {
addElement(t);
return true; // Object grabbed
}
return false; // Object not grabbed
}
}
class TbinList extends Vector { //(*1*)
boolean sort(Trash t) {
Enumeration e = elements();
while(e.hasMoreElements()) {
Tbin bin = (Tbin)e.nextElement();
if(bin.grab(t)) return true;
}
return false; // bin not found for t
}
void sortBin(Tbin bin) { // (*2*)
Enumeration e = bin.elements();
while(e.hasMoreElements())
if(!sort((Trash)e.nextElement()))
System.out.println("Bin not found");
}
}
public class RecycleB {
static Tbin bin = new Tbin(Trash.class);
public static void main(String[] args) {
// Fill up the Trash bin:
ParseTrash.fillBin("Trash.dat", bin);
TbinList trashBins = new TbinList();
trashBins.addElement(
new Tbin(Aluminum.class));
trashBins.addElement(
new Tbin(Paper.class));
trashBins.addElement(
new Tbin(Glass.class));
// add one line here: (*3*)
trashBins.addElement(
new Tbin(Cardboard.class));
trashBins.sortBin(bin); // (*4*)
Enumeration e = trashBins.elements();
while(e.hasMoreElements()) {
Tbin b = (Tbin)e.nextElement();
Trash.sumValue(b);
}
Trash.sumValue(bin);
}
} ///:~