Saturday, February 26, 2011

Visitor Pattern

Visitor lets you define a new operation without changing the classes of the elements on which it operates.

// 1. accept(Visitor) interface
interface Element {
   public void accept( Visitor v ); // first dispatch
}
class ConcreteElement1 implements Element {
   String val=”hello from ConcreteElement1”;
   public void accept( Visitor v ) {
      v.visit( this );
   }
}

// 2. Create a "visitor" base class with a visit() method for every "element" type

interface Visitor {
   public void visit(ConcreteElement1 e ); // second dispatch
}
// 3. Create a "visitor" derived class for each "operation" to perform on "elements"
class ConcreteVisitor1 implements Visitor {
   public void visit(ConcreteElement1 e ) {
      System.out.println( "do concrete operation on ConcreteElement1 e" + e.val );
   }
}

// 4. Client creates "visitor" objects and passes each to accept() calls
class VisitorDemo {br>    public static void main( String[] args ) {
      ConcreteElement1 ce1= new ConcreteElement1();
      ConcreteVisitor1 cv = new ConcreteVisitor1();
      ce1.accept(cv);
   }
}
Visitor Benefits
· Allows you to add operations to a Composite structure without changing the structure itself.
· Adding new operations is relatively easy.
· The code for operation performed by the Visitor is centralized.
Visitor Drawbacks
· The Composite classes’ encapsulation is broken when the Visitor is used.
· Because the traversal function is involved, changes to the Composite structure are more difficult.

No comments:

Total Pageviews

Popular Posts