Guide to Using the State Pattern in C#

Using the State Pattern in C#


In software development, design patterns provide recurring solutions to certain problems. In this article, we will examine how to use the State Pattern design pattern in C#. The State Pattern allows objects to change their behaviors according to their states. In this way, the management of complex state transitions is made easier and more sustainable.

What is the State Pattern?

The State Pattern is a behavioral design pattern that allows an object's behavior to change depending on its internal state. It is typically used to manage the behaviors of objects in different states. This pattern defines a common interface for all states and represents each state as a separate class implementing this interface.

State Pattern Usage Example

For example, a music player can have two states: "Pause" and "Play". In the example below, we will see how these states can be modeled.

1. State Interface

public interface IMusicState
{
    void Play(MusicPlayer context);
    void Pause(MusicPlayer context);
}

2. Playing State

public class PlayingState : IMusicState
{
    public void Play(MusicPlayer context)
    {
        Console.WriteLine("Music is already playing.");
    }

    public void Pause(MusicPlayer context)
    {
        Console.WriteLine("Music paused.");
        context.SetState(new PausedState());
    }
}

3. Paused State

public class PausedState : IMusicState
{
    public void Play(MusicPlayer context)
    {
        Console.WriteLine("Music started playing.");
        context.SetState(new PlayingState());
    }

    public void Pause(MusicPlayer context)
    {
        Console.WriteLine("Music is already paused.");
    }
}

4. Context Class

public class MusicPlayer
{
    private IMusicState _state;

    public MusicPlayer(IMusicState state)
    {
        SetState(state);
    }

    public void SetState(IMusicState state)
    {
        _state = state;
    }

    public void Play()
    {
        _state.Play(this);
    }

    public void Pause()
    {
        _state.Pause(this);
    }
}

Conclusion

Using the State Pattern in C# makes the management of object states extremely simple and flexible. This design pattern increases code comprehensibility in applications with complex state transitions. In scenarios where different object behaviors can change according to state, this pattern provides a great advantage to developers. It is especially useful in game development and user interface applications.