The state design pattern is used when working with objects that go through a variety of states over their lifetime and respond to requests (or change states) based on their current state.
If the state pattern is not used in this situation, the code base will wind up being needlessly complicated, and difficult to maintain due to a large number of conditional blocks. Problems where an object should alter its behavior when its internal state changes are solved using the state pattern.
Take a car for example.
We can change the state of the car. We can use the brakes to slow it down or stop the car and the accelerators to accelerate it up. But the state of the car will change or not depending on the current state of the car. If the car’s engine is started, we can Off it or we can use an accelerator to move the car or we can use the break to stop the car. But if the car’s engine is not yet started or it is OFF, nothing will go to happen if we press the accelerator or breaks it. For a stopped car only possible next state is to ON /start the car’s engine.
- Context: Describes an interface for the client to connect. It keeps track of links to concrete state objects.
- Concrete States: classes that include state-specific functionality
- States: Specifies the actions that each state must do.
- We can add as many states as we want to the context without changing the other states that already exist.
- We do not have to write a large number of conditional blocks for switching between the states.
- If there are few states, it would not be feasible to use this pattern as it would lead to inessential code.
- We should use the state design patterns only if states have complicated logic and state changes often, else it will complicate easy things with too many classes and objects
If you need to prove your skills in the .NET framework, get .NET certified on StudySection. StudySection provides .NET certification exam for beginners as well as experts in the .NET framework. This .NET certification can improve your resume’s success rate.