State pattern allows an object to change its behavior depending on the current values of the object. Consider the figure ‘State pattern example’. It’s an example of a bulb operation. If the state of the bulb is off and you press the switch the bulb will turn off. If the state of bulb is on and you press the switch the bulb will be off. So in short depending on the state the behavior changes.
Figure: - State pattern example
Now let’s try to implement the same bulb sample in C#. Figure ‘State pattern in action’ shows both the class and the client code. We have made a class called as ‘clsState’ which has an enum with two state constants ‘On’ and ‘Off’. We have defined a method ‘PressSwitch’ which toggles its state depending on the current state. In the right hand side of the same figure we have defined a client which consumes the ‘clsState’ class and calls the ‘PressSwitch()’ method. We have displayed the current status on the textbox using the ‘getStatus’ function.
When we click the press switch it toggles to the opposite state of what we have currently.
Figure: - State pattern in action
Asked In: Many Interviews |