109 people like it.

Adapter pattern

Invoke the methods from incompatible types

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
type Cat() = 
    member this.Walk() = printfn "cat walk"
type Dog() = 
    member this.Walk() = printfn "dog walk"

let adapter() = 
    let cat = Cat()
    let dog = Dog()
    let inline walk (x : ^T) = (^T : (member Walk : unit->unit) (x))
    walk(cat)
    walk(dog)
Multiple items
type Cat =
  new : unit -> Cat
  member Walk : unit -> unit

Full name: Script.Cat

--------------------
new : unit -> Cat
val this : Cat
member Cat.Walk : unit -> unit

Full name: Script.Cat.Walk
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Multiple items
type Dog =
  new : unit -> Dog
  member Walk : unit -> unit

Full name: Script.Dog

--------------------
new : unit -> Dog
val this : Dog
member Dog.Walk : unit -> unit

Full name: Script.Dog.Walk
val adapter : unit -> unit

Full name: Script.adapter
val cat : Cat
val dog : Dog
val walk : ('T -> unit) (requires member Walk)
val x : 'T (requires member Walk)
type unit = Unit

Full name: Microsoft.FSharp.Core.unit
Raw view Test code New version

More information

Link:http://fssnip.net/7m
Posted:12 years ago
Author:Tao Liu
Tags: design patterns