Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>An elegant way of avoiding <code>instanceof</code> without inventing some new artificial method in the base class (with a non-descriptive name such as <code>performAction</code> or <code>doWhatYouAreSupposedToDo</code>) is to <strong>use the <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="noreferrer">visitor pattern</a></strong>. Here is an example:</p> <p><strong>Animal</strong></p> <pre><code>import java.util.*; abstract class Animal { String name; public Animal(String name) { this.name = name; } public abstract void accept(AnimalVisitor av); // &lt;-- Open up for visitors. } </code></pre> <p><strong>Lion</strong> and <strong>Deer</strong></p> <pre><code>class Lion extends Animal { public Lion(String name) { super(name); } public void roar() { System.out.println("Roar"); } public void accept(AnimalVisitor av) { av.visit(this); // &lt;-- Accept and call visit. } } class Deer extends Animal { public Deer(String name) { super(name); } public void runAway() { System.out.println("Running..."); } public void accept(AnimalVisitor av) { av.visit(this); // &lt;-- Accept and call visit. } } </code></pre> <p><strong>Visitor</strong></p> <pre><code>interface AnimalVisitor { void visit(Lion l); void visit(Deer d); } class ActionVisitor implements AnimalVisitor { public void visit(Deer d) { d.runAway(); } public void visit(Lion l) { l.roar(); } } </code></pre> <p><strong>TestAnimals</strong></p> <pre><code>public class TestAnimals { public static void main(String[] args) { Animal lion = new Lion("Geo"); Animal deer1 = new Deer("D1"); Animal deer2 = new Deer("D2"); List&lt;Animal&gt; li = new ArrayList&lt;Animal&gt;(); li.add(lion); li.add(deer1); li.add(deer2); for (Animal a : li) a.accept(new ActionVisitor()); // &lt;-- Accept / visit. } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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