05 Dec 2023



Intermediate

The State design pattern is a behavioral pattern that allows an object to alter its behavior when its internal state changes. In C#, the State pattern typically involves the following main components:

  1. Context:

    • Maintains a reference to the current state object.
    • Provides an interface to clients for interacting with the state.
    public class Context
    {
        private State currentState;
    
        public Context(State initialState)
        {
            currentState = initialState;
        }
    
        public void SetState(State newState)
        {
            currentState = newState;
        }
    
        public void Request()
        {
            currentState.Handle();
        }
    }
    
  2. State:

    • Declares an interface for encapsulating the behavior associated with a particular state of the context.
    • May include methods for handling different events.
    public interface State
    {
        void Handle();
    }
    
  3. Concrete States:

    • Implement the State interface to provide specific behavior associated with a particular state.
    public class ConcreteStateA : State
    {
        public void Handle()
        {
            Console.WriteLine("ConcreteStateA is handling the request");
        }
    }
    
    public class ConcreteStateB : State
    {
        public void Handle()
        {
            Console.WriteLine("ConcreteStateB is handling the request");
        }
    }
    
  4. Client:

    • Creates a context and sets its initial state.
    • Interacts with the context, which, in turn, delegates behavior to the current state.
    class Client
    {
        static void Main()
        {
            Context context = new Context(new ConcreteStateA());
    
            // Request is handled by ConcreteStateA
            context.Request();
    
            // Switch to ConcreteStateB
            context.SetState(new ConcreteStateB());
    
            // Request is now handled by ConcreteStateB
            context.Request();
        }
    }
    

In this example:

  • Context is the class that maintains a reference to the current state object and delegates the handling of requests to that state.
  • State is the interface that declares the method for handling requests.
  • ConcreteStateA and ConcreteStateB are concrete implementations of the State interface, providing specific behavior for handling requests in different states.
  • The Client creates a Context and sets its initial state. It then interacts with the context, and the behavior is dynamically delegated to the current state.

The State pattern allows an object to alter its behavior when its internal state changes. It achieves this by representing the states as separate classes and delegating the behavior to the current state object. This promotes flexibility and makes it easier to add new states without modifying the context class.

software-design-patterns
state-design-pattern