47 people like it.

Command pattern for Redo-Undo

Command pattern for redo-undo scenario.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
type Command = { Redo: unit->unit; Undo: unit->unit }

let result = ref 7

let add n = { 
    Redo = (fun _ -> result:= !result + n); 
    Undo = (fun _ -> result := !result - n) }

let minus n = { 
    Redo = (fun _ -> result:= !result - n); 
    Undo = (fun _ -> result := !result + n) }

let cmd = (add 3)
printfn "current state = %d" !result

cmd.Redo()
printfn "after redo: %d" !result

cmd.Undo()
printfn "after undo: %d" !result
Command.Redo: unit -> unit
type unit = Unit

Full name: Microsoft.FSharp.Core.unit
Command.Undo: unit -> unit
val result : int ref

Full name: Script.result
Multiple items
val ref : value:'T -> 'T ref

Full name: Microsoft.FSharp.Core.Operators.ref

--------------------
type 'T ref = Ref<'T>

Full name: Microsoft.FSharp.Core.ref<_>
val add : n:int -> Command

Full name: Script.add
val n : int
val minus : n:int -> Command

Full name: Script.minus
val cmd : Command

Full name: Script.cmd
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Raw view Test code New version

More information

Link:http://fssnip.net/7n
Posted:13 years ago
Author:Tao Liu
Tags: design patterns