Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing API with replaceable backend implementation in .NET (F#)

I'm trying to understand how to implement replaceable components, or a service provider interface, in the .NET world. I suspect that I just don't know the appropriate terminology to search for.

Specifically, I'm playing around with a Matrix class that has different backends. At its simplest, a matrix provides two-parameter get and set methods and a constructor. The implementation is not important to the end user. For instance, depending on the matrices size, the matrix may be backed by an in-memory array, a file, or distributed key-value store. I would like to hide the backend implementation and allow third parties to provide new backend implementations.

An ideal API, called from IronPython, say, might be something like

a = matrix(data = 0, rows = 1000, cols = 10, backend = 'file://test.txt')
a[100, 2] = 1
print a[100, 2]

What should I be reading to understand the pattern for this type of problem?

I am playing around in F# and IronPython, but don't believe this question is specific to any particular .Net language.

like image 236
Tristan Avatar asked Sep 03 '26 02:09

Tristan


1 Answers

Yes, you can create an interface IMatrix and a concrete class that implements it, like that:

type IMatrix =
    abstract Item : (int * int) -> single with get, set

type ConcreteMatrix (data:single[,])=
    interface IMatrix with
        member t.Item with get((x,y)) = data.[x,y]
                      and set((x,y)) value = do data.[x,y] <- value

let printCoordinate (x, y) (matrix : #IMatrix) =
    printf "%A" matrix.[x, y]
like image 178
Stringer Avatar answered Sep 06 '26 01:09

Stringer