Question

Basically, all classes derive from a base class called Element however at any given moment, the structure may contain any derived element.

The visitor is supposed to print the element in several different styles, and implements interface ElementVisitor.

Is it possible to implement the visitor pattern without specifying all derived types in the visitor interface?

If not, what would be alternatives, given that Element and ElementVisitor are framework level components that we are supposed to be able to extend anytime but not edit anytime.

An Element can anytime accept a List<ElementVisitor> like so:

class Element
{
    public void accept(List<ElementVisitor> actions) {
        foreach(ElementVisitor action : actions)
        {
            action.visit(this);
        }
    }
}

Note: the framework is still in its production phase, so the design can still be changed if visitor pattern will not allow this.

Is instanceof the only way around this? What are other alternatives I can look at?

Was it helpful?

Solution

The visitor pattern is a good choice if the operations are going to be extended often. It is, however, not optimally if the elements are going to be extended often. At least as long as the visitor needs functionality of the concrete elements that is not contained in a common ancestor of the elements.

In case the operations implemented via the visitor tend to be more stable than the element classes, it would be better to define the operations as abstract methods in an ancestor or interface implemented by all concrete elements than using the visitor pattern.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top