ReflectiveVisitor

Inigo Surguy presents< an implementation of Visitor pattern based on reflection. I found useful a slight modification of it, that allows for visiting not only the narrowest type, but every type possible , based on the visitAll flag: ReflectiveVisitor.java. This functionality comes in quite handy for tasks such as, for instance, validation. For example, if one has a complex class hierarchy (especially with multiple< inheritance) and different types have different requirements for it to be valid, and a concrete instance may implement a number of those, these validations can be well separated out.

See also:

  1. Visiting Collection elements
  2. Depth-first polymorphism

One thought on “ReflectiveVisitor

  1. Why is reflection so complicated in java? The following code in perl does the same thing — goes up the class heirarchy of the visited class, and finds a visitor method that works. As the untyped language junkie that I am, I wonder if it’s all the typing getting in the way? Or is it just silly to loop over class lists, maybe? In any case, thinking of function calls as messages, then the obvious query “does this class accept the message ‘visit_me’ ? ” makes this really easy.

     sub accept { my $visitor = shift; return ($fn = $visitor->can('visit_gouda')) ? $fn($self) : $self->SUPER::accept($visitor); } 

    Add in

    $visitor->can('visit_' . $self->name ) 

    if you want this to be dynamic and canonical.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s