Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><em>Assuming that there are a number of places where you legitimately need to deal with processing Circle and Square independently,</em> I would deal with the heterogeneous collection by applying the <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="nofollow">Visitor Pattern</a></p> <p>This has the benefit that if you add Triangle later, then when you add a method <code>T visitTriangle(Triangle triangle);</code> to the visitor, your code won't compile until you update every single visitor, avoiding nasty runtime surprises.</p> <p>However... if you're really only talking about a single instance of processing Circle and Square differently, then applying Visitor here is overkill and I would just consider adding an abstract method to Shape for <code>doSomeSpecificUiThing()</code>.</p> <p>It would look something like this:</p> <pre><code>class ShapeVisitor&lt;T&gt; { T visitCircle(Circle circle); T visitSquare(Square square); } class Shape { abstract &lt;T&gt; T accept(ShapeVisitor&lt;T&gt; visitor); // methods of Class Shape } class Circle extends Shape { &lt;T&gt; T accept(ShapeVisitor&lt;T&gt; visitor) { return visitor.visitCircle(this); } // methods of Class Circle } class Square extends Shape { &lt;T&gt; T accept(ShapeVisitor&lt;T&gt; visitor) { return visitor.visitSquare(this); } // methods of Class Square } Class Canvas { void drawAll() { for (Shape s : heterogeneousCollection) { s.draw(); s.accept(new ShapeVisitor&lt;Void&gt;() { @Override Void visitCircle(Circle circle) { circle.xyz(); return null; } @Override Void visitSquare(Square square) { square.abc(); return null; } } } } } </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.
 

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