Tuesday, March 01, 2005

Dining Philosophers and XP : Part 3: The State Pattern Iteration

So I didnt do anything over this weekend. so what? i was very tired after my gym workouts. Anyway, regular readers of my blog (thanks Partha) would have noticed that i have put the source of the first iteration online for your perusing pleasure. The link is mentioned in the previous post. It is also available here.

In the next iteration I started out by implementing the State Pattern for the Philosopher Class. I introduce an abstract class called PhilosopherState to represent the different states that a philosopher can be. These are: Eating, Thinking, Waiting for Right Chopstick, Waiting for left Chopstick and Waiting for both Chopsticks. The PhilosopherState class defines a common interface for all the different states. I then flesh out the waiting states seperately as that would give complete modularization(at least I think so, but am not sure). Maybe in a future iteration I might combine them if convinced otherwise. Subclasses of PhilolosopherState are :
  • PhilosopherEat
  • PhilosopherThink
  • PhilosopherWaitForRightCs
  • PhilosopherWaitForLeftCs
  • PhilosopherWaitForBothCs
I use a Table class which maintains a state object (an instance of a subclass of PhilosopherState) that represents the current state of the Philosopher. This Table class delegates all state-specific requests to the state object. Table uses its PhilosopherState subclass instance to perform operations particular to the state of the philosopher. Whenever the state of philosopher changes the Table class changes the state object it uses.

In the classic definition of terms from GoF the Context is the Table class, State maps to PhilosopherState class and the different subclasses of PhilosopherState class form the ConcreteState classes.

Now, on to avoiding deadlocks. If every philosopher never picks up one Chopstick when he can't get another one, then deadlocks can't occur. So the code includes checks to see if a philosopher can get the other chopstick before he picks up one. This is one of the simplest (albeit cumboresome and unjust) way of avoiding deadlocks.

Links to updated code will follow. I might be editing this post sometime soon to add some more developments instead of adding another post between iterations.


At 10:35 AM, Blogger saswat said...

with my very limited knowledge on patterns, i find the implementation really soothing for the present context and also the modularization of waiting states are really justfiable .Good going!


Post a Comment

<< Home