0

I'm in a situation where one of the states in my FSM needs some information from the outside world to do its job. This information needs to be provided when the transition is requested. What's the best way to accomplish this? At this time I'm using the FSM class as a blackboard to share inforamtion between states.

One really dirty solution could be to have this information cached in the FSM and fill it before requesting the transition and let the state have it from the FSM black board. I don't really like it.

My language is C#

Cheers.

Notbad
  • 5,936
  • 12
  • 54
  • 100
  • How do you handle the FSM itself? It's actually pretty awesome writing SMs using `yield` and `await` - it allows you incredible flexibility and saves a lot of time. But at the very least, you could pass a delegate that the FSM can call when doing the state change. Passing functions is a pretty powerful pattern in general :)) – Luaan May 29 '15 at 14:53
  • Sorry for the dumb question but, what has this delegate to do with the parameter passing? I think I'm missing something. The current state just executes every update, this is the way logic executes. I'm not using yield or await at this moment. Anyway, I think they have nothing to do with the OP question. – Notbad May 29 '15 at 15:06
  • I googled a bit and can't find a built-in FSM implementation on C# so I don't know what class are you using. If it is a third party library you should let us know which one (maybe a link also). If it is your implementation we will need to know the interface at least. – Prusse May 29 '15 at 15:38
  • Maybe this question [Simple state machine example in C#?](http://stackoverflow.com/q/5923767/783219) can help you. – Prusse May 29 '15 at 15:40

1 Answers1

0

To show what I meant by passing a delegate:

class MyStateMachine
{
  private readonly Func<string> askForName;

  public MyStateMachine(Func<string> askForName)
  {
    this.askForName = askForName;
  }

  // ...

  void StateTransitionForActionX()
  {
    var name = askForName();

    // ...
  }
}

public MyStateMachine CreateMachine()
{
  return new MyStateMachine
   (
     () => 
     {
       Console.WriteLine("Please, enter your name: ");
       return Console.ReadLine();
     }
   );
}

Of course, this can be used for any data request whatsoever - using the console just seemed like a simple way to illustrate the idea :) Closures in particular can be pretty powerful.

Luaan
  • 62,244
  • 7
  • 97
  • 116
  • This is a nice way to do it. Anyway I have gone the "event" way. My state machine at this time supports an event name or a event class to be passed (this is because ussualy just an event name is enough, which is just an int) to the enter method. This way it can be stored by the state and be used later. – Notbad Jun 03 '15 at 14:01