70 people like it.

Command pattern for Redo-Undo II

This command redo-undo implement group the command under Do/Undo category.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
type CommandType = 
    | Deposit
    | Withdraw
type TCommand = 
    | Command of CommandType * int

let result = ref 7
let deposit x = result := !result + x
let withdraw x = result := !result - x
let Do = fun (cmd:TCommand) ->
    match cmd with
    | Command(CommandType.Deposit, n) -> deposit n
    | Command(CommandType.Withdraw,n) -> withdraw n
let Undo = fun (cmd:TCommand) ->
    match cmd with
    | Command(CommandType.Deposit, n) -> withdraw n
    | Command(CommandType.Withdraw,n) -> deposit n

printfn "current balance %d" !result
let depositCmd = Command(Deposit, 3)
Do depositCmd
printfn "after deposit: %d" !result
Undo depositCmd
printfn "after undo: %d" !result
union case CommandType.Deposit: CommandType
union case CommandType.Withdraw: CommandType
type TCommand = | Command of CommandType * int

Full name: Script.TCommand
union case TCommand.Command: CommandType * int -> TCommand
type CommandType =
  | Deposit
  | Withdraw

Full name: Script.CommandType
Multiple items
val int : value:'T -> int (requires member op_Explicit)

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

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
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 deposit : x:int -> unit

Full name: Script.deposit
val x : int
val withdraw : x:int -> unit

Full name: Script.withdraw
val Do : cmd:TCommand -> unit

Full name: Script.Do
val cmd : TCommand
val n : int
val Undo : cmd:TCommand -> unit

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

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val depositCmd : TCommand

Full name: Script.depositCmd
Raw view Test code New version

More information

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