【发布时间】:2011-05-05 14:18:58
【问题描述】:
我正在尝试实现命令模式来控制机器人。我正在使用它来探索如何在 F# 中实现命令模式。下面是我的实现:
type Walle(position, rotate) =
let (x:float,y:float) = position
let rotation = rotate
member this.Move(distance) =
let x2 = distance * sin (System.Math.PI/180.0 * rotation)
let y2 = distance * cos (System.Math.PI/180.0 * rotation)
let newPosition = (x+x2, y+y2)
Walle(newPosition, rotation)
member this.Rotate(angle) =
let newRotation =
let nr = rotation + angle
match nr with
| n when n < 360.0 -> nr
| _ -> nr - 360.0
Walle(position, newRotation)
let Move distance = fun (w:Walle) -> w.Move(distance)
let Rotate degrees = fun (w:Walle) -> w.Rotate(degrees)
let remoteControl (commands:List<Walle->Walle>) robot =
commands |> List.fold(fun w c -> c w)
let testRobot() =
let commands = [Move(10.0);Rotate(90.0);Move(16.0);Rotate(90.0);Move(5.0)]
let init = Walle((0.0,0.0),0.0)
remoteControl commands init
为了想出一个功能性的解决方案,我选择让机器人的动作在每次调用后在其新位置返回一个新的机器人实例(避免突变)。我还让命令函数关闭了执行操作所需的状态。
我很好奇人们在实现该模式时是否认为这些是好的设计决策?或者,如果人们可以就实施该模式提供任何其他建议?
【问题讨论】:
标签: design-patterns f#