Note that there are some explanatory texts on larger screens.

plurals
  1. POseek better design to have multi-dispatching with java
    primarykey
    data
    text
    <p>In a language not supporting multiple dispatching, such as Java, the code would probably look something like this </p> <pre><code>/* Example using run time type comparison via Java's "instanceof" operator */ interface Collideable { void collideWith(Collideable other); } class Asteroid implements Collideable { public void collideWith(Collideable other) { if (other instanceof Asteroid) { System.out.println("AAAAAA"); } else if (other instanceof Spaceship) { System.out.println("BBBBBB"); } else if (other instanceof Plane) { System.out.println("CCCCCCC"); } } } class Spaceship implements Collideable { public void collideWith(Collideable other) { if (other instanceof Asteroid) { System.out.println("DDDDDDD"); } else if (other instanceof Spaceship) { System.out.println("EEEEEEE"); } else if (other instanceof Plane) { System.out.println("FFFFFFF"); } } } class Plane implements Collideable { public void collideWith(Collideable other) { if (other instanceof Asteroid) { System.out.println("GGGGGGG"); }else if (other instanceof Spaceship) { System.out.println("HHHHHHH"); }else if (other instanceof Plane) { System.out.println("KKKKKK"); } } } </code></pre> <p>As the visitor pattern can help to solve this problem, I'm thinking if I should impl each leaf class with void collideWith() { visitor.visit(this); // visitor is set in the setter }</p> <pre><code>interface Visitor { void visit(Collideable c); void visit(Asteroid c); void visit(Spaceship c); void visit(Plane c); } </code></pre> <p>Then each unique println should be implemented in subclass of visitor as below? </p> <pre><code>class AsteroidVisitor implements Visitor { void visit(Collideable c) {} void visit(Asteroid c) { System.out.println("AAAAAA"); } void visit(Spaceship c) { System.out.println("BBBBBBB"); } void visit(Plane c) { System.out.println("CCCCCC"); } } //etc for SpaceshipVisitor and PlaneVisitor() </code></pre> <p>Is it the best way to deal with this kind of refactoring to replace instanceof?</p> <p>EDIT: The print out is just example of unique operations in each method, not the ultimate result. I modify my example to be clear.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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