This project is read-only.
State pattern

Category:
Design patterns
Description: State pattern implementation shows how a class's internal state can change its behavior. For more information, please go to http://en.wikipedia.org/wiki/Factory_method_pattern
Code:
type AccountState = 
| Overdrawn
| Silver
| Gold
[] type USD
type Account<[] 'u>() =
let mutable balance = 0.0<_>
member this.State
with get() =
match balance with
| _ when balance <= 0.0<_> -> Overdrawn
| _ when balance > 0.0<_> && balance < 10000.0<_> -> Silver
| _ -> Gold
member this.PayInterest() =
let interest =
match this.State with
| Overdrawn -> 0.
| Silver -> 0.01
| Gold -> 0.02
interest * balance
member this.Deposit(x:float<_>) =
let (a:float<_>) = x
balance <- balance + a
member this.Withdraw(x:float<_>) = balance <- balance - x

let state() =
let account = Account()
account.Deposit(10000.)
printfn "interest = %A" (account.PayInterest())
account.Withdraw(20000.)
printfn "interest = %A" (account.PayInterest())

Execution Result:
interest = 200.0
interest = 0.0

Last edited Sep 14, 2011 at 4:27 AM by ttliu2000, version 1

Comments

No comments yet.