Below is my attempt at implementing the factory method design pattern using F# whilst trying to make it a little more functional (i.e. not a straight OO implementation). Below is what I came up with:
type ISkateBoard = abstract Model : unit -> string
type SkateBoard =
| Roskopp
| Peters
interface ISkateBoard
with member this.Model() =
match this with
| Roskopp-> "Rob Roskopp..."
| Peters -> "Duane Peters..."
let assemble model : ISkateBoard =
match model with
| "Roskopp" -> Roskopp :> ISkateBoard
| "Peters" -> Peters :> ISkateBoard
| _ -> failwith "no such skateboard model.."
let SkateBoardFactory assemble model = assemble model
let SantaCruzFactory = SkateBoardFactory assemble
Is this an appropriate implementation of the factory method design pattern? Is the pattern used in real world F# applications?
I’m not sure to what extent is the factory method design pattern useful in functional programming.
The goal of the pattern is to hide the creation of objects, so that you can work with just an abstract representation of the object.
Your factory method could take a concrete type (e.g. discriminated union) as an argument, instead of string. Then the task of the factory is to build abstract representation from the concrete representation:
Now, a factory would be simply a function of type
SkateBoard -> ISkateBoard. For example (using F# object expressions):I think that the benefit of this approach is that you can do some work on the concrete representation of the type (e.g. some calculation where you need pattern matching), but then you can use the
factoryto turn the concrete type into an abstract type.This matches quite well with the usual approach in functional programming – you often use differenet representations of one data and transform between them (depending on which representation is better for a particular problem).