문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top