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.
Saturday, February 26, 2011
Subscribe to:
Post Comments (Atom)
Blog Archive
Total Pageviews
Popular Posts
-
Early men used improvised devices to tell their position on the globe. Following is the Latitude Hook of the Polynesians . It is used to...
-
When you first open visio and go to File ->New->Getting Started-> Software and Database ->Database Model Diagram-> (from Fil...
-
How did early man attempt to discover the circumference of the earth without ever traveling it? This is how it was accomplished by a man ...
-
We hope this and all knowledge is used for the benefit of humankind : to encourage us towards love and kindness and goodness. Men have at...
-
How would one measure the height of a mountain if one only had a quadrant (for measuring angle)? A Quadrant A quadrant is as illustrate...
-
The question of how to tell longitude accurately was contested for a very long time. People had figured out how to tell latitude by use o...
-
I looked online and (in two books) but did not find very good explanations of ternary search trees. Following is what I combined together fr...
-
This was an easy one to do. I volunteered to help some people at the office and they mistakenly thought I was a "DB2 expert" despi...
-
(see discussion ) Step 1 : install JDK 1.5+ and above Step 2: check JAVA_HOME is set Step 3: install the rjb gem gem install rjb -v 1.1....
No comments:
Post a Comment