Visitor Pattern


Where an Object Structure allows a Visitor (i.e. an operation) to apply over each Element (i.e. the data) within that Object Structure, thereby allowing the system to accommodate new operations (in the form of new Visitors) without changing the class hierarchy of the Object Structure (i.e. the Element's class definitions, themselves).

This pattern increases the ease of adding new operations by trading off an increased difficulty of modifying the shape of the Elements.


  • often requires that Visitor implementations have more-private-than-designed access to Elements, thereby breaking those classes' encapsulation.


  1. Visitor — the object doing the visiting, encapsulates an "operation"
  2. Element — the object being visited, encapsulates the "data"
  3. "Object Structure" — the container of elements.

Visitor Pattern In Action

Ruby: Enumerable.each

In duck-type languages, like Ruby, the Element need not provide specific accommodations for the visitor.

object_structure = [ { :name => "Philip" }, { :age => 10 }, { :address => "1113 Happy Lane" } ]
object_structure.each do |element|
  #this block is the Visitor
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License