Decorate pattern

Category:
Design patterns
Description: Decorate pattern implementation shows how we can add new functionality (check zero) dynamically. For more information, please go to http://en.wikipedia.org/wiki/Decorator_pattern
Code:
type Divide() = 
let mutable divide = fun (a,b) -> a / b
member this.Function
with get() = divide
and set(v) = divide <- v
member this.Invoke(a,b) = divide (a,b)

let decorate() =
let d = Divide()
let checkZero (a,b) = if b = 0 then failwith "a/b and b is 0" else (a,b)
try
d.Invoke(1, 0) |> ignore
with e -> printfn "without check, the error is = %s" e.Message
d.Function <- checkZero >> d.Function
try
d.Invoke(1,0) |> ignore
with e -> printfn "after add check, error is = %s" e.Message

Execution Result:
without check, the error is = Attempted to divide by zero.
after add check, error is = a/b and b is 0

Last edited Sep 14, 2011 at 3:26 AM by ttliu2000, version 1

Comments

No comments yet.