Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Monday, 15 July 2013

Implementing Visitor Pattern in Java

The Visitor design pattern provides a way to separate algorithms from the object structure. A consequence of this separation is the ability to add new operations to existing object structures without modifying those structures. In design patterns, the authors define the Visitor Pattern as
Represent an operation to be performed on the elements of an object structure.
Visitor lets you define a new operation without changing the classes
of the elements on which it operates.

Skip to Sample Code

The idea is to have two class hierarchies
  1. One for the elements being operated on, where each element has an "accept" method that takes a visitor object as an argument
  2. One for the visitors that define operations on the elements. Each visitor has a visit() method for each element class.
The accept() method of the element class calls back the visit() method passing itself as an argument. Here is the UML diagram for the Visitor Pattern, followed by a brief description of the actors involved.Visitor Pattern UML
  • Visitor: Declares the visit method.
  • ConcreteVisitor: An implementation of the Visitor interface. May also store state if required.
  • Element (or Visitable): The interface that declares the accept method. The accept method invokes the visit method passing itself as an argument.
  • ConcreteElement: Element of the object structure. Has to implement accept method (implements Element).

When to Use
Use the Visitor pattern when
  1. There is a need perform operations that depend on concrete classes of an object structure, and the structure may contain classes of objects with differing interfaces.
  2. Distinct and unrelated operations must be performed on objects in an object structure, and you want to avoid distributing/replicating similar operations in their classes
  3. The classes defining the object structure rarely change, but new operations may be added every once in a while.

Pros and Cons
  • Easy to add new operations: To add a new operation, you only have to add a new Visitor implementation. There is no need to change the element classes.
  • Gather related operations: Visitor pattern helps gather related operations into the visitor, while the unrelated behavior is implemented in the individual elements.
  • Visiting across class hierarchies: Unlike iterators, visitors may visit objects in an object structure which need not have objects of the same type.
  • State Management: Visitors can keep track of state changes with each visit. Without a visitor, state has to be passed as an argument.
  • Hard to add new concrete elements: Adding a ConcreteElement involves adding a new operation to the Visitor interface and a corresponding implementation in each concrete visitor implementation. Visitor pattern is best used in cases where the object structure is stable but the set of operations may change frequently.
  • Breaking Encapsulation: Visitor pattern often forces you to provide public operations to access the internal state of the elements, which compromises encapsulation.

Visitor Pattern and Double Dispatch
Double dispatch is a mechanism that allows a function call to change depending on the runtime types of multiple objects involved in the call. In single dipatch a call like Integer.compareTo(Object o), the actual function call depends only on the calling object (the Integer object here). In double dispatch, the actual call may also depend on the object being passed as a parameter to the compareTo method.
The most common programming languages (except for LISP) do not have a way for implementing double dispatch. But you may implement double dispatch in these programming languages using the Visitor pattern. You can see the implementation in the following example. Here the call to accept depends not only on the type of object on which it is called (MyLong or MyInteger) but also on the parameter that is being passed to it (AddVisitor and SubtractVisitor).
package visitor;

interface Visitor {
public int visit(MyInteger wheel);

public int visit(MyLong engine);
}

interface Visitable {
public int accept(Visitor visitor);
}

class MyInteger implements Visitable {
private int value;

MyInteger(int i) {
this.value = i;
}

public int accept(Visitor visitor) {
return visitor.visit(this);
}

public int getValue() {
return value;
}
}

class MyLong implements Visitable {
private long value;

MyLong(long l) {
this.value = l;
}

public int accept(Visitor visitor) {
return visitor.visit(this);
}

public long getValue() {
return value;
}
}

class SubtractVisitor implements Visitor {
int value;

public SubtractVisitor(int value) {
this.value = value;
}

public int visit(MyInteger i) {
System.out.println("Subtract integer");
return (i.getValue() - value);
}

public int visit(MyLong l) {
System.out.println("Subtract long");
return ((int) l.getValue() - value);
}

}

class AddVisitor implements Visitor {
int value;

public AddVisitor(int value) {
this.value = value;
}

public int visit(MyInteger i) {
System.out.println("Adding integer");
return (value + i.getValue());
}

public int visit(MyLong l) {
System.out.println("Adding long");
return (value + (int) l.getValue());
}

}

public class VisitorTest {
public static void main(String[] args) {
AddVisitor cv = new AddVisitor(10);
SubtractVisitor sv = new SubtractVisitor(10);
MyInteger i = new MyInteger(20);
MyLong l = new MyLong(20);
System.out.println(i.accept(cv));
System.out.println(l.accept(cv));

System.out.println(i.accept(sv));
System.out.println(l.accept(sv));

}
}
VisitorTest.java

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...