Version française
Home     About     Download     Resources     Contact us    
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 =
     object('self)
         method show: unit
         method next: 'self
     end

class ['state] context s =
     object(_:'self)
         val state_: #state = s
         method show = state_#show
         method run = {< state_ = state_#next >}
     end

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

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

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 
design.


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