我有一个演员需要抽象,因为它被用作许多地方使用的常见模式。
if Int(AgeFrom)!...Int(AgeTO)! ~= Int(age)! {
print("yes")
}
现在说我需要自定义一个actor实现来处理Message2的逻辑,为了实现这个目的,我有哪些选项?
答案 0 :(得分:8)
receive
函数是PartialFunction[Any, Unit]
,因此我们可以利用此功能。部分函数提供了一些可以使用的有用运算符,例如PartialFunction#orElse
。
这意味着您可以在父actor中定义PartialFunction[Any, Unit]
然后在子actor中定义另一个,并通过组合它们来定义receive。我们来看一些代码!
abstract class Parent extends Actor {
def commonReceive: Receive = {
case CommonHandledMessage =>
println("common handling")
case Message =>
println("parent handling")
}
}
class Child extends Actor {
override val receive: Receive = specializedReceive orElse commonReceive
def specializedReceive: Receive = {
case Message =>
println("child handling")
}
}
但是,您应该小心组合这些部分函数的方式,因为您可能会对结果感到惊讶。当您使用orElse合并器时,部分函数基本上叠加在一起。因此,您可以想象我们上面定义的receive
方法转换为:
override val receive: Receive = {
case Message =>
println("child handling")
case CommonHandledMessage =>
println("common handling")
case Message =>
println("parent handling")
}
这意味着父处理在这里基本没用,因为你可以从模式匹配中扣除。
我想这里的观点总是考虑如何组合这些部分函数,因为可能永远不会达到某些模式匹配分支。在这种情况下,永远不会达到父处理,因为它基本上是覆盖。除此之外,部分功能真的很酷!
我希望有帮助:)