Duplicate of: When Should I Use The Visitor Design Pattern
Why would someone want to use the visitor pattern? I've read a couple of articles, but I'm not getting something.
If I need a function to bill a custom, I could use
Custom.Accept(BillVisitor)
or something like
Bill(Customer)
The second is less complex, and the Bill function is still separated from the Customer class. So why would I want to use the visitor pattern?
The issue arises when you have a complex structure, i.e., a hierarchy or something else that's not simply linear. When you can't simply iterate over the structure, a visitor is very handy.
If I have a hierarchy (or tree), each Node has a list of children. When I want to apply a process to every node in the tree, it's pleasant to create a Visitor.
A Node can then apply the Visitor to itself, and each of its child Nodes. Each child, transitively, does the same (apply the Visitor to itself and then any children).
This use of a Visitor works out very nicely.
When you have a super-simple data structure, Visitor doesn't add a lot of value.