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: Michael Wohlwend <micha-1@f...>
Subject: state pattern...
Hi,

although it can be implemented with a 'match', just of interest, can somebody 
help me with my oo implementation of the state-pattern?

this does not work (any many other tries also didn't :-)

class ['a] context (start_state : 'a)= object(this)
 constraint 'a = #state
 val mutable state = start_state
 method set_state st = state <- st
 method show = state#show
 method run = state#handle this 
end

and virtual state = object
  method virtual show : unit
  method virtual handle : state #context -> #state -> unit
end;;

class state1 = object (this)
 inherit state
 method show = print_endline "state1"
 method handle context = context#set_state (new state2)
end
and state2 = object (this)
 inherit state
 method show = print_endline "state2"
 method handle context = context#set_state (new state1)
end;;

for this to work:
let c = new context (new state1) in
c#show; (* state1 *)
c#run; (* change state *)
c#show; (* state2 *)
c#run;


cheers,
 Michael