0

I'm trying to avoid using a singleton pattern with my finite state machine.

My agent is changing states based on enumerated messages:

public enum MessageType : byte
    {
        PathFollow,
        AlertStatusStart
    }

Each state is derived from the following class that has access to a Game1 class:

public abstract class State
    {
        protected Game1 game;

        /// <summary>
        /// This will execute when the state is entered
        /// </summary>
        /// <param name="agent"></param>
        public abstract void Enter(IAgent agent);

        /// <summary>
        /// This will execute when the state is exited
        /// </summary>
        /// <param name="agent"></param> 
        public abstract void Exit(IAgent agent);

        /// <summary>
        /// This executes if the agent receives a message from the message dispatcher
        /// </summary>
        /// <param name="agent"></param>
        /// <param name="pTelegram"></param>
        /// <returns></returns>
        public abstract bool OnMessage(IAgent agent, Telegram pTelegram);

        /// <summary>
        /// This is the state's normal update function
        /// </summary>
        /// <param name="agent"></param>
        public abstract void Update(IAgent agent);
    }

If I want to change between each state I could create a new instance of the state to change to:

agent.FSM.ChangeState(new ClassDerivedFromState(game1));

However, if I only ever want one class instance per state and I'm avoiding the idea of singletons (mainly due to the non parameterless constructor) then I have decided to use a dictionary for all agent states:

Dictionary<MessageType, State> States { get; }

Then the state can be changed using:

agent.FSM.ChangeState(agent.States[MessageType.AlertStatusStart]);

This has the downside of limiting me to one state per message type but I guess that shouldn't be a problem.

Can someone please tell me if I going down the right path with this idea?

Edited by DaveTran: n/a

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by DaveTran
0

Without knowing what you are trying to do it's hard to tell :) But you have effectively created a singleton factory but using a dictionary instead of class for the factory.

0

Brilliant. That means I can also use constructors with parameters then. Winner! :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.