More On Visitors

Things to remember about the Visitor design pattern:

 

Example

Here is an example that illustrates how the visitor will always deliver correct behavior for the given host type.

See the Documentation

Download the code:: MaleFemale.java

The host is an APerson. There are two types of concrete hosts: Male and Female.

The visitors are ITasks. There are 3 kinds of concrete visitors: EatTask, GetDressedTask and WeekendTask.

The Tasker object randomly selects either a Male or a Female host to execute the supplied ITask (visitor) with the supplied parameter. The correct behavior for the selected host will always be run.

Here is a typical DrJava Interactions pane session:

Welcome to DrJava.
> Tasker tasker = new Tasker();
> ITask getDressedTask = new GetDressedTask();
> ITask eatTask = new EatTask();
> ITask weekendTask = new WeekendTask();
> tasker.doTask(eatTask, "steak")
Male host selected:

"You got a beer to go with that steak?"
> tasker.doTask(eatTask, "steak")
Male host selected:

"You got a beer to go with that steak?"
> tasker.doTask(eatTask, "steak")
Female host selected:

"No thanks, may I have a salad with dressing on the side, please?"
> tasker.doTask(getDressedTask, null)
Female host selected:

"I'll be ready in a minute!"
> tasker.doTask(getDressedTask, null)
Male host selected:

"Does "black tie" mean I can't wear shorts?"
> tasker.doTask(getDressedTask, null)
Male host selected:

"Does "black tie" mean I can't wear shorts?"
> tasker.doTask(weekendTask, "9")
Female host selected:

"Only have 9 hours, so let's clean the house, wash the clothes and weed the garden!"
> tasker.doTask(weekendTask, "9")
Female host selected:

"Only have 9 hours, so let's clean the house, wash the clothes and weed the garden!"
> tasker.doTask(weekendTask, "9")
Male host selected:

"Where's the remote?"
>