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 <- rtn as String: "Shape handler"
render()
-> shape as Polygon
<- rtn as String: "Polygon handler"
render()
-> shape as Square
<- rtn as String: "Square handler"
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
#!ek9 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
E05030 — Every level of the hierarchy that is extended must be 'as open'. Square extends Quadrilateral, so a Quadrilateral that is not open is rejected with E05030. See ek9 -h E05030 for details.
Incorrect:
Quadrilateral is Polygon
Correct:
Quadrilateral is Polygon as open
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: cost-based, deep, dispatcher, hierarchy, resolution, specific