Dispatch on a deep class hierarchy where exact match wins over parent handler.

← Design Patterns and Idioms · Ref: Q1123

Most specific handler wins via cost-based selection:

  render() as dispatcher -> shape as Shape
  render() -> shape as Polygon
  render() -> shape as Square

Passing Quadrilateral selects Polygon handler (closest match). Passing Square selects Square handler (exact), not Polygon.

See Q1121 for sealed dispatch. See Q1122 for fallback handling.

Example

defines module qa.designpatterns.dispatcherdeep

  defines class

    Shape as abstract
      default operator ?

    Polygon is Shape as open
      default operator ?

    Quadrilateral is Polygon as open
      default operator ?

    Square is Quadrilateral
      default operator ?

    GeometryRenderer

      render() as dispatcher
        -> shape as Shape
        <- rtn as String: "Shape handler"

      render()
        -> shape as Polygon
        <- rtn as String: "Polygon handler"

      render()
        -> shape as Square
        <- rtn as String: "Square handler"

  defines program

    DispatcherDeepDemo()
      stdout <- Stdout()
      renderer <- GeometryRenderer()

      //Polygon -> Polygon handler
      stdout.println(renderer.render(Polygon()))

      //Quadrilateral -> Polygon handler (closest match)
      stdout.println(renderer.render(Quadrilateral()))

      //Square -> Square handler (exact match beats Polygon)
      stdout.println(renderer.render(Square()))

Common mistakes

E01010 — EK9 has no instanceof. The dispatcher automatically selects the most specific handler.

Incorrect:

      if shape instanceof Square

Correct:

      render() as dispatcher
        -> shape as Shape
Other ways to ask this
  • I have Shape -> Polygon -> Quadrilateral -> Square and need the most specific handler
  • In Java I'd check instanceof in order. Show how EK9 dispatcher picks the best match
  • Given a deep hierarchy, verify that a Square handler wins over a Polygon handler
  • Set up dispatcher resolution across multiple inheritance levels

Coming from another language?

Java: ordered instanceof checks (fragile). C#: pattern matching with type guards. EK9: dispatcher with automatic cost-based resolution — most specific handler wins.

Keywords: resolution, dispatcher, specific, hierarchy, deep, cost-based