原文地址:[url]http://java.dzone.com/articles/visitor-pattern-re-visited[/url]
Understanding the problem
The actual problem is not the naming and horrible API verbosity of visiting code, but the mis-understanding of the pattern. It’s not a pattern that is best suited for visiting large and complex data structures with lots of objects of different types. It[color=red]’s the pattern that is best suited for visiting simple data structures with few different types, but visiting them with hundreds of visitors.[/color] Take files and folders. That’s a simple data structure. You have two types. One can contain the other, both share some properties. Various visitors could be:
CalculateSizeVisitor
FindOldestFileVisitor
DeleteAllVisitor
FindFilesByContentVisitor
ScanForVirusesVisitor
… you name it
I still dislike the naming, but the pattern works perfectly in this paradigm.
Understanding the problem
The actual problem is not the naming and horrible API verbosity of visiting code, but the mis-understanding of the pattern. It’s not a pattern that is best suited for visiting large and complex data structures with lots of objects of different types. It[color=red]’s the pattern that is best suited for visiting simple data structures with few different types, but visiting them with hundreds of visitors.[/color] Take files and folders. That’s a simple data structure. You have two types. One can contain the other, both share some properties. Various visitors could be:
CalculateSizeVisitor
FindOldestFileVisitor
DeleteAllVisitor
FindFilesByContentVisitor
ScanForVirusesVisitor
… you name it
I still dislike the naming, but the pattern works perfectly in this paradigm.