Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is the "Visitor Pattern With Default", in which you do the visitor pattern as normal but then define an abstract class that implements your <code>IShapeVisitor</code> class by delegating everything to an abstract method with the signature <code>visitDefault(IShape)</code>.</p> <p>Then, when you define a visitor, extend this abstract class instead of implementing the interface directly. You can override the <code>visit</code>* methods you know about at that time, and provide for a sensible default. However, if there really isn't any way to figure out sensible default behavior ahead of time, you should just implement the interface directly.</p> <p>When you add a new <code>IShape</code> subclass, then, you fix the abstract class to delegate to its <code>visitDefault</code> method, and every visitor that specified a default behavior gets that behavior for the new <code>IShape</code>.</p> <p>A variation on this if your <code>IShape</code> classes fall naturally into a hierarchy is to make the abstract class delegate through several different methods; for example, an <code>DefaultAnimalVisitor</code> might do:</p> <pre><code>public abstract class DefaultAnimalVisitor implements IAnimalVisitor { // The concrete animal classes we have so far: Lion, Tiger, Bear, Snake public void visitLion(Lion l) { visitFeline(l); } public void visitTiger(Tiger t) { visitFeline(t); } public void visitBear(Bear b) { visitMammal(b); } public void visitSnake(Snake s) { visitDefault(s); } // Up the class hierarchy public void visitFeline(Feline f) { visitMammal(f); } public void visitMammal(Mammal m) { visitDefault(m); } public abstract void visitDefault(Animal a); } </code></pre> <p>This lets you define visitors that specify their behavior at whatever level of specificity you wish.</p> <p>Unfortunately, there is no way to avoid doing something to specify how visitors will behave with a new class - either you can set up a default ahead of time, or you can't. (See also the second panel of <a href="http://xkcd.com/568/" rel="noreferrer">this cartoon</a> )</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload