Skip to the guide

Iterator and visitor

AdvancedPattern7 pages

Both patterns deal with a structure of many objects, such as an online course made of sections, lessons and quizzes. Iterator lets a caller walk the structure without knowing how it is stored, and Visitor adds an operation without changing the classes it runs on. The 1994 book Design Patterns gives Iterator's intent as "provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation." It gives Visitor's as "represent an operation to be performed on the elements of an object structure." Interviewers ask about Iterator now and then and rarely ask for Visitor by name, so they listen for which change you expect.

A shopping centre's guard and its inspectors

Think of a big shopping centre with shops, restaurants and arcades that hold more shops. A night guard carries a route card. She asks it for the next door, so she never needs the floor plan, and she can stop for coffee and carry on from the same door.

Inspectors come through too, a fire inspector one week and a tax inspector the next. Each carries one form per kind of unit. At every door, the unit says "I'm a restaurant, use your restaurant form." A new inspector changes nothing in the centre. A new kind of unit, such as a gym, sends every inspector back to the office for a new form.