1

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?

2
  • 3
    Why don't you like this design? Oct 27, 2010 at 15:35
  • 2
    I think this design violate Open-Closed Principle. This structure is repeated over all drived classes.
    – Hieu Phan
    Oct 27, 2010 at 16:23

1 Answer 1

6

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

Btw., this question is better suited for StackOverflow.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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