Wednesday, December 25, 2013

Visitor Pattern

Visitor Pattern

I was doing a bit of research on visitor pattern. It was quite confusing at first as various sites were focusing on different points of this pattern. Following is my understanding of visitor pattern.

Motivation
  • Allows new operations to be defined and used on element of an object structure without changing the contents of those elements.(Actual reason)
  • Visitor design pattern is a way of separating an algorithm from an object structure on which it operates.(Its just the result of what happens when you implement previous point)
  • Double dispatch(It is how visitor pattern internally work)

UML Diagram




Element :- Interface containing Accept method taking Visitor type as parameter.

Concrete Element :- Classes in which we intend to add functionality in future

Object Structure :- Collection of objects or composite object. It should have provision to iterate over each concrete element so that Accept method can be called.

Visitor :- Interface containing function for each Concrete element taking same as paramater. If we have 10 concrete elements then Visit interface will have 10 functions.

Concrete Visitor :- Concrete class implementing Visitor interface. We can have n number of concrete visitors depending on the number of functionality we need to add.


Advantages

  • Extending the functionality of a class hierarchy by an external class.
  • Adding new operations is easy.
  • Related behavior isn't spread over classes defining the object structure, its localized in visitor.
  • Unrelated set of behavior are partitioned in own visitor subclass.
  • Simulate double dispatch.
Disadvantages

  • Adding new ConcreteElement class is difficult as each new ConcreteElement gives rise to new abstract operation on visitor and corresponding implementation in every ConcreteVisitor class.
  • The ConcreteElement interface must be powerful enough to let visitor do their job. You may be forced to provide public operations that access an elements internal state, which may compromise its encapsulation.
  • Breaks Dependency Inversion Principle (DIP) : DIP states that a class should depend upon abstract classes and not concrete classes (Martin 2000). It is one of the object oriented class design principles which help in managing the module dependencies and thus preventing the rotting of design. The Visitor interface depends upon the ConcreteVisitable classes thus breaking the DIP (Xiao‐Peng and Yuan‐Wei 2010). 

Sample code link : https://github.com/cdeepakait/VisitorPattern.git

References

  • http://hillside.net/guruplop/1_OntologicalVisitorPattern.pdf
  • http://www.oodesign.com/visitor-pattern.html
  • http://en.wikipedia.org/wiki/Visitor_pattern
  • http://www.youtube.com/watch?v=pL4mOUDi54o