调度的目标是动态决定在您的函数中执行的操作.
如果你有一个(动态)调度函数它是主要的(或者只有,如果你不需要转换或其他转换),则责任是决定调用哪个其他函数.决定通常基于调用方法的实例的类型,或某些参数的类型,但它也可以取决于例如参数的值或某些配置值.
调度规则可以是硬编码的(使用例如scala中的模式匹配),或者可以来自调度表.
正如你所提到的,有几种变体,比如单调度(具体方法取决于调用原始方法的实例,这是一种基本的OO机制),double dispatch(根据运行时类型调度函数调用不同的具体函数)呼叫中涉及的多个对象).
相关的设计模式是Visitor,它允许您动态地向现有类添加一组函数,并在其核心还具有动态调度.
当您在调度方法内部或某些初始化代码(ef用于调度表)中定义具体方法时,会出现嵌套的块/闭包.
调度基于参数值,硬编码决策和调度表的情况的简单示例:
class Dispatch {
def helloJohn(): String = "Hello John"
def helloJoe(): String = "Hello Joe"
def helloOthers(): String = "Hello"
def sayHello(msg: String): String = msg match {
case "John" => helloJohn()
case "Joe" => helloJoe()
case _ => helloOthers()
}
val fs = Map("John" -> helloJohn _, "Joe" -> helloJoe _)
def sayHelloDispatchTable(msg: String): String = fs.get(msg) match {
case Some(f) => f()
case _ => helloOthers()
}
}
Run Code Online (Sandbox Code Playgroud)