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
state pattern...
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2005-06-26 (22:13)
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 <jhw@wetware.com>
that's my village calling... no doubt, they want their idiot back.