Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have a base class Shape, and drived classes Line Segment, Arc, B-spline,... I want to find the intersection point between these shapes. I would like:

Shape* a = new LineSegment();
Shape* b = new Arc();

bool did_intersect = a->Intersect(b);

I don't like this design in Intersect:

bool LineSegment(Shape* s) {
  Arc* arc = dynamic_cast<Arc*>(s);
  if (NULL != arc)
    return LineSegmentArcIntersection(this, arc);

  BSpline* bspline = dynamic_cast<BSpline*>(s);
  if (NULL != bspline)
    return LineSegmentBSplineIntersection(this, bspline);
  ...
}

So, What design pattern is best suitable with this context?

share|improve this question
3  
Why don't you like this design? –  Robert Harvey Oct 27 '10 at 15:35
2  
I think this design violate Open-Closed Principle. This structure is repeated over all drived classes. –  Hieu Phan Oct 27 '10 at 16:23
add comment

1 Answer

I think you are looking for double dispatch or multiple dispatch.

Btw., this question is better suited for StackOverflow.

share|improve this answer
    
Effective C++ by Scott Meyers has a great article on double dispatch talking at great detail on how to implement it also! –  brainydexter Mar 22 '12 at 13:47
    
Could you please answer stackoverflow.com/questions/11425993/… ? –  Lijo Jul 11 '12 at 6:48
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.