谁说visitor不可以添加新元素?

07-02-08 xysniper
这个visitor就可以随便添加,利用反射就可以做到了.

public abstract class Visitor {

final public void visit(Object object) {

Method method = getVisitMethod(object);

try {

method.invoke(this, new Object[] { object });

} catch (Exception e) {

String message = "invokeing method failed:visit("

+ object.getClass().getName() + ")";

throw new RuntimeException(message, e);

}

}

private Map visitMethods = new HashMap();

private Method getVisitMethod(Object object) {

//return (Method) visitMethods.get(object.getClass());

Iterator it = visitMethods.keySet().iterator();

for (; it.hasNext();) {

Class clazz = (Class) it.next();

if (clazz.isAssignableFrom(object.getClass())) {

return (Method) visitMethods.get(clazz);

}

}

throw new RuntimeException("method: visit(" + object.getClass().getName()

+ ") undefined in the class");

}

private Method visitMethod;

private void initVisitMethod() {

Method[] methods = getClass().getDeclaredMethods();

for (int i = 0; i < methods.length; i++) {

if (methods.getName().equals("visit")) {

Class[] paramTypes = methods.getParameterTypes();

if (paramTypes.length == 1) {

visitMethods.put(paramTypes[0], methods);

}

}

}

}

{

initVisitMethod();

}

}

具体的Visitor

public class PrintVisitor extends Visitor{

public void visit(Float f){

System.out.println("float:"+f);

}

public void visit(Date date){

System.out.println("date:"+date);

}

public void visit(String str){

System.out.println("string:"+str);

}

}

public class PrintVisitor2 extends Visitor{

public void visit(String str){

System.out.println("string2:"+str);

}

public void visit(List list){

System.out.println("list2:"+list);

}

}

public void testVisit(){

ArrayList list = new ArrayList();

list.add("a");

list.add("b");

Visitor v = new PrintVisitor();

v.visit("hello");

v.visit(new Date());

Visitor v1 = new PrintVisitor2();

v1.visit("hello");

v1.visit(list);

}

youngjiang
2007-03-09 17:02
兄弟,辛苦啦,顶一下下

Coolyu0916
2007-03-10 22:44
this is a Visitor???

猜你喜欢