State Pattern Implementation

Suicidal Isaac

New member
Joined
Aug 1, 2025
Messages
3
Programming Experience
Beginner
I watched a tutorial video about the State design pattern, but the video showed the pattern implementation in such a way that adding a new state would require changing the previous states and the class itself, in which these states are used, which, in my opinion, violates the OCP.

So I wrote a different implementation, in which you can add new states and new actions applicable to these states, simply by creating a new class that implements the abstract state class.

Did I do everything correctly, or did I implement the pattern incorrectly?

P.S. I have only been learning Csharp for a week

The code is on github, but I will also provide screenshots
 

Attachments

  • Program.png
    Program.png
    32.1 KB · Views: 2
  • TrafficLight.png
    TrafficLight.png
    42.8 KB · Views: 3
  • TrafficLightActions.png
    TrafficLightActions.png
    15 KB · Views: 3
  • ITrafficLightState.png
    ITrafficLightState.png
    17.1 KB · Views: 3
  • TrafficLightState.png
    TrafficLightState.png
    63.9 KB · Views: 3
  • GreenState.png
    GreenState.png
    69.3 KB · Views: 3
  • RedState.png
    RedState.png
    69.4 KB · Views: 3
  • YellowState.png
    YellowState.png
    69.1 KB · Views: 2
  • EmergencyState.png
    EmergencyState.png
    46.5 KB · Views: 3
  • OffState.png
    OffState.png
    46.1 KB · Views: 2
Do not post screenshots of code. They are essentially unreadable, specially on small devices. Post code as text in code tags. You can use the button that looks like this on this forum's toolbar </> to easily get a dialog box where you can paste in the code, and then get the resulting text in code tags.

Nothing in the State design pattern requires that the states know about each other. It's very likely the tutorial you were watching was conflating the State design pattern with the Finite State Machines.

Notice that one of the problems that the State design pattern tries to solve is exactly not having to touch other stuff:
State-specific behavior should be defined independently. That is, adding new states should not affect the behavior of existing states.
from: State pattern - Wikipedia
 
Back
Top Bottom