ChoJin’s Quarter
Computer Sciences, Cooking, Photography and Filmmaking…
Observer Design Pattern in OCaml

Posted on Tuesday 16 January 2007

So, I've been programming again for a couple of weeks now (for myself I mean, of course I never stopped programming at work). When re-opening my files I realized I hadn't coded since 2004, and even back then, I wasn't very active. What I feared would happen had happened... Working all day long on a computer cuts the willingness to program at home, even though I have a lot of interesting personal projects in my "TODO" list.

Anyway, I'm back at it and here is a small module for the OCaml language I implemented while working on my current project.

This is an implementation of the classic OOP Observer Design Pattern but implemented as a module (I first did an object oriented version but I later realized it was not necessary). I use it to be able to automagically update the GUI's views whenever the data changes.

You'll find this module at the Programming page.

Here is an example of how to use the imperative version:

  1. open ObservableImp
  2.  
  3. let _ =
  4.   let observable = Observable.make 0 in
  5.   let callback value = print_endline (string_of_int value) in
  6.   Observable.add_observer "mycallback" callback observable;
  7.   Observable.set 42 observable;
  8.   Observable.remove_observer "mycallback";
  9.   Observable.set 51;

The Observer Design Pattern is really much agreeable to use in OCaml than C++. In C++ you would have to create an abstract class which defines a virtual function for the callback and use inheritance to implement it. In OCaml you can pass any function as a callback, even a method from an object without requiring inheritance. This greatly reduces the overhead of using such design pattern.

That's it for today!

Share this story using:These icons link to social bookmarking sites where readers can share and discover new web pages.

No comments have been added to this post yet.

Leave a comment

(required)

(required)


Information for comment users
Line and paragraph breaks are implemented automatically. Your e-mail address is never displayed. Please consider what you're posting.

Use the buttons below to customise your comment.


Comment moderation is in use. Please do not submit your comment twice -- it will appear shortly.

RSS feed for comments on this post | TrackBack URI