Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between visitor design pattern and depth first search?

A depth first search seem able to perform similar functions as the visitor design pattern. A visitor allows you to define some data structures and add operations on those structures (in the form of multiple visitors) as needed without modifying the structures themselves. A description of the visitor pattern is provided on wikipedia. If we do a depth first search (or any other graph search algorithm like breadth first search) on the data structure, and every time an element of the structure is found, we run our desired operation, then this seems to perform the same function as the visitor. For example, consider a tree. Even if some nodes of the tree have different type, we can still check for the node types when doing DFS and then perform different operations based on the node type.

like image 681
john Avatar asked Jun 09 '11 20:06

john


2 Answers

A depth-first search is just that--a search. A Visitor pattern is orthogonal to a depth-first search, in the sense that a Visitor doesn't necessarily care how the tree is traversed; it just knows what it needs to do on/to/with each node.

like image 72
NRitH Avatar answered Oct 09 '22 13:10

NRitH


You can have Visitor implementation without having DFS. Similarly, you can do a DFS without use of the Visitor pattern. They are completely separate.

I happen to agree with the implication that they could be used together in an elegant way.

As a note, for the canonical Visitor pattern the objects being visited need to implement some sort of AcceptVisitor interface -- the clause "without modifying the structures themselves" in your question leads me to question whether you are doing that.

like image 44
hvgotcodes Avatar answered Oct 09 '22 14:10

hvgotcodes