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

阅读更多


这个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[i].getName().equals("visit")) {
                Class[] paramTypes = methods[i].getParameterTypes();
                if (paramTypes.length == 1) {
                    visitMethods.put(paramTypes[0], methods[i]);
                }
            }
        }
    }

    {
        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);
    }

你可能感兴趣的:(C,C++,C#,F#)