16.8 RTTI 真的有害吗
16.8 RTTI 真的有害吗
本章的各种设计方案都在努力避免使用
然而,
我们的例子同样建立在
//: DynaTrash.java
// Using a Hashtable of Vectors and RTTI
// to automatically sort trash into
// vectors. This solution, despite the
// use of RTTI, is extensible.
package c16.dynatrash;
import c16.trash.*;
import java.util.*;
// Generic TypeMap works in any situation:
class TypeMap {
private Hashtable t = new Hashtable();
public void add(Object o) {
Class type = o.getClass();
if(t.containsKey(type))
((Vector)t.get(type)).addElement(o);
else {
Vector v = new Vector();
v.addElement(o);
t.put(type,v);
}
}
public Vector get(Class type) {
return (Vector)t.get(type);
}
public Enumeration keys() { return t.keys(); }
// Returns handle to adapter class to allow
// callbacks from ParseTrash.fillBin():
public Fillable filler() {
// Anonymous inner class:
return new Fillable() {
public void addTrash(Trash t) { add(t); }
};
}
}
public class DynaTrash {
public static void main(String[] args) {
TypeMap bin = new TypeMap();
ParseTrash.fillBin("Trash.dat",bin.filler());
Enumeration keys = bin.keys();
while(keys.hasMoreElements())
Trash.sumValue(
bin.get((Class)keys.nextElement()));
}
} ///:~
尽管功能很强,但对
ParseTrash.fillBin("Trash.dat", bin.filler());
为产生这个指针,我们采用了一个“匿名内部类”(已在第
对这个设计,要注意的一个地方是尽管没有设计成对归类加以控制,但在
通过前面那些例子的学习,
Enumeration keys = bin.keys();
while(keys.hasMoreElements())
Trash.sumValue(
bin.get((Class)keys.nextElement()));
就象大家看到的那样,新类型向系统的加入根本不会影响到这些代码,亦不会影响