visitor模式的常用之处在于,它将对象集合的结构和对集合所执行的操作分离开来。例如,它可以将一个编译器中的分析逻辑和代码生成逻辑分离开来。有了这样的分离,想使用不同的代码生成器就会很容易。更大的好处还有,其它一些公用程序,如lint,可以在使用分析逻辑的同时免受代码生成逻辑之累。不幸的是,向集合中增加新的对象往往需要修改已经写好的visitor类。本文提出了一种在java中实现visitor模式的更灵活的方法:使用reflection(反射)。
集合(collection)普遍应用于面向对象编程中,但它也经常引发一些和代码有关的疑问。例如,"如果一个集合存在不同的对象,该如何对它执行操作?"
一种方法是,对集合中的每个元素进行迭代,然后基于所在的类,对每个元素分别执行对应的操作。这会很难办,特别是,如果你不知道集合中有什么类型的对象。例如,假设想打印集合中的元素,你可以写出如下的一个方法(method):
public void messyprintcollection(collection collection) {
iterator iterator = collection.iterator()
while (iterator.hasnext())
system.out.println(iterator.next().tostring())
}
这看起来够简单的了。它只不过调用了object.tostring()方法,然后打印出对象,对吗?但如果有一组哈希表怎么办?事情就会开始变得复杂起来。你必须检查从集合中返回的对象的类型:
public void messyprintcollection(collection collection) {
iterator iterator = collection.iterator()
while (iterator.hasnext()) {
object o = iterator.next();
if (o instanceof collection)
messyprintcollection((collection)o);
else
system.out.println(o.tostring());
}
}
不错,现在已经解决了嵌套集合的问题,但它需要对象返回string,如果有其它不返回string的对象存在怎么办?如果想在string对象前后添加引号以及在float后添加f又该怎么办?代码还是越来越复杂:
public void messyprintcollection(collection collection) {
iterator iterator = collection.iterator()
while (iterator.hasnext()) {
object o = iterator.next();
if (o instanceof collection)
messyprintcollection((collection)o);
else if (o instanceof string)
system.out.println("""+o.tostring()+""");
else if (o instanceof float)
system.out.println(o.tostring()+"f");
else
system.out.println(o.tostring());
}
}
可以看到,事情的复杂度会急剧增长。你当然不想让一段代码到处充斥着if-else语句!那怎么避免呢?visitor模式可以帮你。
要实现visitor模式,得为访问者建立一个visitor接口,还要为被访问的集合建立一个visitable接口。然后,让具体类实现visitor和visitable接口。这两个接口如下所示:
public interface visitor
{
public void visitcollection(collection collection);
public void visitstring(string string);
public void visitfloat(float float);
}
public interface visitable
{
public void accept(visitor visitor);
}
对于具体的string,可能是这样:
public class visitablestring implements visitable
{
private string value;
public visitablestring(string string) {
value = string;
}
public void accept(visitor visitor) {
visitor.visitstring(this);
}
}
在accept方法中,对this类型调用正确的visitor方法:
visitor.visitstring(this)
这样,就可以如下实现具体的visitor:
public class printvisitor implements visitor
{
public void visitcollection(collection collection) {
iterator iterator = collection.iterator()
while (iterator.hasnext()) {
object o = iterator.next();
if (o instanceof visitable)
((visitable)o).accept(this);
}
public void visitstring(string string) {
system.out.println("""+string+""");
}
public void visitfloat(float float) {
system.out.println(float.tostring()+"f");
}
}
实现visitablefloat和visitablecollection类的时候,它们也是各自调用合适的visitor方法,所得到的效果和前面那个用了if-else的messyprintcollection方法一样,但这里的手法更干净。在visitcollection()中,调用的是visitable.accept(this),然后这个调用又返回去调用一个合适的visitor方法。这被称做 "双分派";即,visitor先调用了visitable类中的方法,这个方法又回调到visitor类中。
虽然通过实现visitor消除了if-else语句,却也增加了很多额外的代码。最初的string和float对象都要用实现了visitable接口的对象进行包装。这有点讨厌,但一般说来不是问题,因为你可以让经常被访问的集合只包含那些实现了visitable接口的对象。
但似乎这还是额外的工作。更糟糕的是,当增加一个新的visitable类型如visitableinteger时,会发生什么呢?这是visitor模式的一个重大缺陷。如果想增加一个新的visitable对象,就必须修改visitor接口,然后对每一个visitor实现类中的相应的方法一一实现。你可以用一个带缺省空操作的visitor抽象基类来代替接口。那就很象java gui中的adapter类。那个方法的问题在于,它需要占用单继承;而你往往想保留单继承,让它用于其它什么东西,比如继承stringwriter。那个方法还有限制,它只能够成功访问visitable对象。
幸运的是,java可以让visitor模式更灵活,使得你可以随心所欲地增加visitable对象。怎么做?答案是,使用reflection。比如,可以设计这样一个reflectivevisitor接口,它只需要一个方法:
public interface reflectivevisitor {
public void visit(object o);
}
就这样,很简单。至于visitable,还是和前面一样,我过一会儿再说。现在先用reflection来实现printvisitor:
public class printvisitor implements reflectivevisitor {
public void visitcollection(collection collection)
{ ... same as above ... }
public void visitstring(string string)
{ ... same as above ... }
public void visitfloat(float float)
{ ... same as above ... }
public void default(object o)
{
system.out.println(o.tostring());
}
public void visit(object o) {
// class.getname() returns package information as well.
// this strips off the package information giving us
// just the class name
string methodname = o.getclass().getname();
methodname = "visit"+
methodname.substring(methodname.lastindexof(".")+1);
// now we try to invoke the method visit
try {
// get the method visitfoo(foo foo)
method m = getclass().getmethod(methodname,
new class[] { o.getclass() });
// try to invoke visitfoo(foo foo)
m.invoke(this, new object[] { o });
} catch (nosuchmethodexception e) {
// no method, so do the default implementation
default(o);
}
}
}
现在不需要visitable包装类。仅仅只是调用visit(),请求就会分发到正确的方法上。很不错的一点是,只要认为适合,visit()就可以分发。这并非必须使用reflection--它可以使用其它完全不同的机制。
新的printvisitor中,有针对collection,string和float而写的方法,但然后它又在catch语句中捕捉所有未处理的类型。你要扩展visit()方法,使得它也能够处理所有的父类。首先,得增加一个新方法,称为getmethod(class c),它返回的是要调用的方法;为了找到这个相匹配的方法,先在类c的所有父类中寻找,然后在类c的所有接口中寻找。
protected method getmethod(class c) {
class newc = c;
method m = null;
// try the superclasses
while (m == null && newc != object.class) {
string method = newc.getname();
method = "visit" + method.substring(method.lastindexof(".") + 1);
try {
m = getclass().getmethod(method, new class[] {newc});
} catch (nosuchmethodexception e) {
newc = newc.getsuperclass();
}
}
// try the interfaces. if necessary, you
// can sort them first to define "visitable" interface wins
// in case an object implements more than one.
if (newc == object.class) {
class[] interfaces = c.getinterfaces();
for (int i = 0; i < interfaces.length; i++) {
string method = interfaces[i].getname();
method = "vis
闽公网安备 35060202000074号