Visitor Design Pattern

Download the working example demo code in java from my GIT repository -https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects

Example code description : This is an interesting example which includes a Party. So the Party class has music, drinks and food. For the preparation Party Host class accepts visitor cooks  (Veg cook and Non-Veg cook). So the combination could be of a week end party / a week day party in which you can have veg / non veg cooked food. Please download and run the program once. Without using  pattern if we put logic in “if else conditions” them it could had been messy and maintaining it could had been a night mare.Visitor patter is blessing in disguise of use cases like these.

visitor3
Intent
  • Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
  • The classic technique for recovering lost type information.
  • Do the right thing based on the type of two objects.
  • Double dispatch
Problem

Many distinct and unrelated operations need to be performed on node objects in a heterogeneous aggregate structure. You want to avoid “polluting” the node classes with these operations. And, you don’t want to have to query the type of each node and cast the pointer to the correct type before performing the desired operation.

public class Feeder {
    public void feed(Dog d) {
        d.eat();
    }
    public void feed(Cat c) {
        c.eat();
    }
}
 
Feeder feeder = new Feeder();
Object o = new Dog();
feeder.feed(o); // Cannot compile!
This issue is called double dispatch as it requires calling a method based on both instance and parameter types, which Java doesn’t handle natively. In order to make it compile, the following code is required:

if (o instanceof Dog) {
    feeder.feed((Dog) o);
} else if (o instanceof Cat) {
    feeder.feed((Cat) o);
} else {
    throw new RuntimeException(“Invalid type”);
}

 

This gets even more complex with more overloaded methods available – and exponentially so with more parameters. In maintenance phase, adding more overloaded methods requires reading the whole if stuff and updating it. Multiple parameters are implemented through embedded ifs, which is even worse regarding maintainability. The Visitor pattern is an elegant way to achieve the same, with no ifs, at the expense of a single method on the Animal class.

public interface Animal {
    void eat();
    void void accept(Visitor v);
}
 
public class Cat {
    public void eat() { … }
    public void accept(Visitor v) {
        v.visit(this);
    }
}
 
public class Dog {
    public void eat() { … }
    public accept(Visitor v) {
        v.visit(this);
    }
}
 
public class FeederVisitor {
    public void visit(Cat c) {
        new Feeder().feed(c);
    }
    public void visit(Dog d) {
        new Feeder().feed(d);
    }
}

Discussion

Visitor’s primary purpose is to abstract functionality that can be applied to an aggregate hierarchy of “element” objects. The approach encourages designing lightweight Element classes – because processing functionality is removed from their list of responsibilities. New functionality can easily be added to the original inheritance hierarchy by creating a new Visitor subclass.

The Visitor pattern makes adding new operations (or utilities) easy – simply add a new Visitor derived class. But, if the subclasses in the aggregate node hierarchy are not stable, keeping the Visitor subclasses in sync requires a prohibitive amount of effort.

An acknowledged objection to the Visitor pattern is that is represents a regression to functional decomposition – separate the algorithms from the data structures. While this is a legitimate interpretation, perhaps a better perspective/rationale is the goal of promoting non-traditional behavior to full object status.

visitor_taxi

Let us take an example of Taxi. You (Person – domain object ) wants to visit a new a place in city. Now you do not want to implement the driving logic in your domain object. So you can add accept visitor method object in which the Taxi object might contain and execute the logic for you .

 

Check list
  1. Confirm that the current hierarchy (known as the Element hierarchy) will be fairly stable and that the public interface of these classes is sufficient for the access the Visitor classes will require. If these conditions are not met, then the Visitor pattern is not a good match.
  2. Create a Visitor base class with a visit(ElementXxx) method for each Element derived type.
  3. Add an accept(Visitor) method to the Element hierarchy. The implementation in each Element derived class is always the same – accept( Visitor v ) { v.visit( this ); }. Because of cyclic dependencies, the declaration of the Element and Visitor classes will need to be interleaved.
  4. The Element hierarchy is coupled only to the Visitor base class, but the Visitor hierarchy is coupled to each Element derived class. If the stability of the Element hierarchy is low, and the stability of the Visitor hierarchy is high; consider swapping the ‘roles’ of the two hierarchies.
  5. Create a Visitor derived class for each “operation” to be performed on Element objects.visit() implementations will rely on the Element’s public interface.
  6. The client creates Visitor objects and passes each to Element objects by calling accept().
Rules of thumb
  • The Visitor pattern is like a more powerful Command pattern because the visitor may initiate whatever is appropriate for the kind of object it encounters.
  • The Visitor pattern is the classic technique for recovering lost type information without resorting to dynamic casts.

Visitor Vs Strategy

The strategy pattern is like a 1:many relationship. When there is one type of object and I want to apply multiple operations to it, I use the strategy pattern. I think of the visitor pattern as a many:many relationship.
A Visitor is like an extended Strategy that is polymorphic at two dimensions: the code executed doesn’t only depend on the actual strategy used, but also on the parameter passed to it.
Strategy, State, Command, Visitor (and more I’m sure) all have some behavior built into an object that we can pass around, so they all have a very similar feeling when you’re building the object. Their “intent” is subtly different and yet sometimes overlapping.
Visitor is often (but not always) a way to add new functionality to an existing object graph. The example I learned on is an HTML parser that builds a DOM of objects on an HTML page and invites me to add functionality via visitors.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s