Decorate pattern

implement the decorate pattern in F#. The decorate pattern is to add new featuures to an object at runtime.

Copy Source
Copy Link
Tools:
 1: type Divide() = 
 2:     let mutable divide = fun (a,b) -> a / b
 3:     member this.Function
 4:         with get() = divide
 5:         and set(v) = divide <- v
 6:     member this.Invoke(a,b) = divide (a,b)
 7: 
 8: let decorate() = 
 9:     let d = Divide()
10:     let checkZero (a,b) = if b = 0 then failwith "a/b and b is 0" else (a,b)
11:     
12:     try 
13:         d.Invoke(1, 0) |> ignore
14:     with e -> printfn "without check, the error is = %s" e.Message
15: 
16:     d.Function <- checkZero >> d.Function 
17:     try
18:         d.Invoke(1,0) |> ignore
19:     with e -> printfn "after add check, error is = %s" e.Message
20: 
type Divide =
  class
    new : unit -> Divide
    member Invoke : a:int * b:int -> int
    member Function : (int * int -> int)
    member Function : (int * int -> int) with set
  end

Full name: Snippet.Divide
val mutable divide : (int * int -> int)
val a : int

  type: int
  implements: System.IComparable
  implements: System.IFormattable
  implements: System.IConvertible
  implements: System.IComparable<int>
  implements: System.IEquatable<int>
  inherits: System.ValueType
val b : int

  type: int
  implements: System.IComparable
  implements: System.IFormattable
  implements: System.IConvertible
  implements: System.IComparable<int>
  implements: System.IEquatable<int>
  inherits: System.ValueType
val this : Divide
property Divide.Function: int * int -> int
val set : seq<'T> -> Set<'T> (requires comparison)

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.set
val v : (int * int -> int)
member Divide.Invoke : a:int * b:int -> int

Full name: Snippet.Divide.Invoke
val decorate : unit -> unit

Full name: Snippet.decorate
val d : Divide
val checkZero : ('a * int -> 'a * int)
val a : 'a
val failwith : string -> 'T

Full name: Microsoft.FSharp.Core.Operators.failwith
member Divide.Invoke : a:int * b:int -> int
val ignore : 'T -> unit

Full name: Microsoft.FSharp.Core.Operators.ignore
Multiple items
val e : exn

  type: exn
  implements: System.Runtime.Serialization.ISerializable
  implements: System.Runtime.InteropServices._Exception


--------------------

val e : exn

  type: exn
  implements: System.Runtime.Serialization.ISerializable
  implements: System.Runtime.InteropServices._Exception
val printfn : Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val e : exn

  type: exn
  implements: System.Runtime.Serialization.ISerializable
  implements: System.Runtime.InteropServices._Exception
property System.Exception.Message: string

More information

Link: http://fssnip.net/7i
Posted: 2 years ago
Author: Tao Liu (website)
Tags: Design Patterns