F#的实现
本文描述的方式也可以运用在在F#中。首先自然还是接口的定义:
type IPingMessageHandler =
abstract Ping : Ping -> unit
abstract Finish : unit -> unit
and IPongMessageHandler =
abstract Pong : Pong -> unit
以上便是F#中定义接口的方式,与C#相比更为简洁。接着便是Ping类型的实现:
and Ping() =
inherit (IPongMessageHandler -> unit) Actor()
let mutable count = 5
override self.Receive(message) = message self
member self.Start(pong : Pong) =
pong << fun h -> self |> h.Ping
interface IPongMessageHandler with
member self.Pong(pong) =
printfn "Ping received pong"
count <- count - 1
if (count > 0) then
pong << fun h -> self |> h.Ping
else
pong << fun h -> h.Finish()
self.Exit()
Pong类型的实现则更为简单:
and Pong() =
inherit (IPingMessageHandler -> unit) Actor()
override self.Receive(message) = message self
interface IPingMessageHandler with
member self.Ping(ping) =
printfn "Pong received ping"
ping << fun h -> self |> h.Pong
member self.Finish() =
printfn "Finished"
self.Exit()
启动乒乓测试:
(new Pong()) |> (new Ping()).Start;