This project is read-only.
Strategy pattern

Design patterns
Description: Strategy pattern shows the underlying algorithm can be changed dynamically by setting the function from outside. For more information, please go to
let quicksort l = 
printfn "quick sort"
let shellsort l =
printfn "shell short"
let bubblesort l =
printfn "bubble sort"
type Strategy() =
let mutable sortFunction = fun _ -> ()
member this.SetStrategy(f) = sortFunction <- f
member this.Execute(n) = sortFunction(n)

let stragegy() =
let s = Strategy()

Execution Result:
quick sort

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


evanescentdevil Sep 28, 2013 at 12:36 AM 
// Different Approach
// Put all the strategies as a static members for a class that can't be instantiated

type GoStrategies =
----static member Driving = printfn "I'm Driving"
----static member Flying = printfn "I'm Flying"
----static member Swimming = printfn "I'm Swimming"

type Vehicle() =
----member val Brand = "" with get,set
----member val Model = "" with get,set
----abstract Type :string with get
----abstract member Go :unit -> unit
----member O.Print() = printfn "%s\t%s\t%s" O.Type O.Brand O.Model

type Car() =
----inherit Vehicle()
----override O.Type with get() = "Car"
----override O.Go() = GoStrategies.Driving

type Plane() =
----inherit Vehicle()
----override O.Type with get() = "Plane"
----override O.Go() = GoStrategies.Flying

type Boat() =
----inherit Vehicle()
----override O.Type with get() = "Boat"
----override O.Go() = GoStrategies.Swimming

// Testing
let car1 = Car( Brand="BMW", Model="X6" )
let car2 = Car( Brand="Dodge", Model="Viper" )
let plane1 = Plane( Brand="AirBus", Model="A321" )

Thorium Mar 3, 2012 at 10:53 AM 
Warning: Object-oriented code in functional language!
Why would you ever need a Strategy-"holder" as you could execute or send the function as parameter in the first place?