Search code examples
design-patternsvisitor-pattern

Shouldn't the visitor pattern be refactored?


Currently I'm working on a project which utilizes the Visitor Pattern. While working with this pattern I found myself writing comments like:

* @param VisitorInterface $visitor The visitor to visit.

The visitor pattern consists of the following interfaces:

VisitorInterface {
    public function visit($object);
}

VisitableInterface {
    public function accept(VisitorInterface $visitor);
}

Now my question: shouldn't it be the opposite?

VisitorInterface {
    public function accept($object);
}

VisitableInterface {
    public function visit(VisitorInterface $visitor);
}

Because now the visitor will accept something to visit, since a visitor should be something visiting something. While the visitable object will now accept a visitor.

Eg:

class Party implements VisitableInterface {
    public function visit(VisitorInterface $visitor) {
        $visitor->accept($this);
    }
}

class Human implements VisitorInterface {
    public function accept($object) {
        // do something with object
    }
}

So now we have a party that accepts visitors. These visitors can be asked to accept something from the party to do something with.

I hope to have explained my thoughts on this well enough to show my "concern". Please don't blame me for trying to break a design pattern :-)


Solution

  • Method is called on object with parameters, not on parameters. So, if you call human.visit(party), it means that human visits something, and in parameter you specified what - party.