Here is an example. Let’s say you wrote code to enumerate all the directories and files in a directory tree on disk.
Let’s say you wanted then to:
You encapsulate your logic in a Visitor object you present to each node in a directory tree on disk. In might have a two methods:
The enumerating womb might provide service methods for the Visitors, e.g. delete and extract.
With this structure, you don’t need to meddle with your tree spanning code every time you invent a new Visitor. Further, you can use your Visitor code on anything else that is a collection of dirs and files, e.g. a flat file list, a database… Your Visitors work unmodified. Because you have separated out the logic of spanning the collection from the logic of processing a member, you can you mix and match, plugging them together any way you want.
The problem in designing a Visitor is deciding just how much information to present to the Visitor. If you present too much, you limit the contexts is which your Visitors can be used. If you present too much, you waste time collecting information the Visitor never uses. If you present too little, you won’t be able to handle future problems with the impoverished Visitor interface. You can ameliorate this problem by creating layered Visitor interfaces and then using only as many of the layers as you need to in your Visitor, and implementing as many as you can on a given collection.
As you add Visitors, you may well discover you want to refactor your code and change the interface to more smoothly accomodate all the various problems you want to solve with Visitors. It is easier to refactor early.
Unfortunately, I have not encountered a standard set of battle-hardened Visitor interfaces to use.
The alternative way of looking at the problem is to write specialised Iterators for all your collections. A one-shot Visitor become a loop body or a methods called as a loop body. The Visitor pattern can be more selective. It does not need to visit every element in a collection.
![]() |
and suggestions to improve this page to Roedy Green : | ||
| Canadian Mind Products | |||
| mindprod.com IP:[65.110.21.43] | |||
| Your face IP:[38.103.63.16] | The information on this page is for non-military use only. | ||
| You are visitor number 7,279. | Military use includes use by defence contractors. | ||
| You can get a fresh copy of this page from: | or possibly from your local J: drive (Java virtual drive/Mindprod website mirror) | ||
| http://mindprod.com/jgloss/visitor.html | J:\mindprod\jgloss\visitor.html | ||