我正在尝试使用命令模式来控制机器人。我正在使用这个来探索如何在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
为了提供一个可用的解决方案,我选择让机器人的动作在每次调用后返回一个新的机器人实例(避免突变)。同时,我也让命令函数包含执行这些动作所需的状态。
我想知道在实现这种模式时,人们是否认为这些是好的设计决策?或者,是否有其他建议可以提供?