State pattern in C#

The state design patterns is a behavioral pattern that implements a state machine in an object-oriented way. It allows an object/class to alter its behavior when its internal state changes.

Lets say that we have a competition application that allows clients to register score, but only when the competition is open. A non state pattern design would maybe look like this.

This may work for the time being, but when we add more and more of different boolean properties we need to check things all over the code and testing will be a pain.

The code below implements the state pattern.

Yes, it is a lot more code but it will follow the single responsibility principle, and it will be more easy to test.

Leave a Comment

Your email address will not be published. Required fields are marked *