Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
state pattern...
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: james woodyatt <jhw@w...>
Subject: Re: [Caml-list] state pattern...
On 26 Jun 2005, at 12:57, Michael Wohlwend wrote:
> although it can be implemented with a 'match', just of interest, can 
> somebody
> help me with my oo implementation of the state-pattern?

I tend to work in the functional style first, then transfer what I've 
done into imperative style if there is a performance gain to be had by 
it.  Here's what I would do to make something like what you want:

class type state =
         method show: unit
         method next: 'self

class ['state] context s =
         val state_: #state = s
         method show = state_#show
         method run = {< state_ = state_#next >}

class state1 =
         method show = print_endline "state1"
         method next = new state2
and state2 =
         method show = print_endline "state2"
         method next = new state1

let c = new context (new state1) in
let c = c#run in
let c = c#run in

You get into a problem pretty quickly if the state class needs to be 
aware of the full type of the context in order to compute the next 
state.  What that really means is that the context *is* the state, and 
you need to rethink how the pattern is supposed to be applied to your 

j h woodyatt <>
that's my village calling... no doubt, they want their idiot back.