English version
Accueil     Ŕ propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis ŕ jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml ŕ l'adresse ocaml.org.

Browse thread
The Bridge Pattern in OCaml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2008-03-19 (16:29)
From: Christopher L Conway <cconway@c...>
Subject: The Bridge Pattern in OCaml
It is often said that almost any programming problem can be solved
without touching the OO part of OCaml. I have found this to be largely
true and try to avoid using objects whenever possible. One design
pattern that comes up frequently that I have never found a suitable
non-OO solution for is the Bridge Pattern.

In short, the Bridge Pattern is applicable when a client needs access
to operations F, G which can be provided by a variety of underlying
implementations X, Y, or Z. If the specific implementation isn't
important, you create an interface B (a "bridge") with operations F
and G, and write both the client and the implementations to the
interface B. The client should then be able to access X, Y, or Z
interchangeably, e.g., by taking the implementation as an argument at

This is trivial in any OO language (including OCaml using objects) and
will typically appear in the first or second chapter of any tutorial
on OO programming. This is more or less *the* problem that subtyping
polymorphism was designed to solve. My question: is there a non-OO way
of achieving the same result in OCaml?

The naive approach is to substitute module and module types for
objects and interfaces in the OO solution. I'm sure everybody who's
come to OCaml from an OO background has tried this approach and found
it wanting. The problem is you can't "pass around" a module as if it
were an object. You have to do an explicit branch to choose between X,
Y, and Z anytime you access F or G. (Even if you functorize the client
C, you end up having to explicitly branch to choose between C(X),
C(Y), C(Z).)

Another solution is to define a structure type including F and G, then
pass the structure around as a "dictionary." I.e., to code up a
fragment of the object type system by hand in order to avoid dealing
with objects in their fully generality. This doesn't work if the
interface needs to include types as well as functions.

At this point, I typically give up and go with the OO solution. Has
anyone come up with an elegant solution that does not require objects
and object subtyping?