Interview question, state pattern
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
(I) Can you explain strategy pattern?
Strategy pattern are algorithms inside a class which can be interchanged depending on the class used. This pattern is useful when you want to decide on runtime which algorithm to be used.
Let’s try to see an example of how strategy pattern works practically. Let’s take an example of a math’s calculation where we have strategies like add and substract. Figure ‘Strategy in action’ shows the same in a pictorial format. It takes two numbers and the depending on the strategy it gives out results. So if it’s an addition strategy it will add the numbers, if it’s a substraction strategy it will give the substracted results. These strategies are nothing but algorithms. Strategy pattern are nothing but encapsulation of algorithms inside classes.
Figure: - Strategy in action
So the first thing we need to look in to is how these algorithms can be encapsulated inside the classes. Below figure ‘Algorithm encapsulated’ shows how the ‘add’ is encapsulated in the ‘clsAddStatergy’ class and ‘substract’ in the ‘clsSubstractStatergy’ class. Both these classes inherit from ‘clsStratergy’ defining a ‘calculate’ method for its child classes.
Figure: - Algorithms encapsulated
Now we define a wrapper class called as ‘clsMaths’ which has a reference to the ‘clsStatergy’ class. This class has a ‘setStatergy’ method which sets the strategy to be used.
Figure: - Strategy and the wrapper class
Below figure ‘Strategy client code’ shows how the wrapper class is used and the strategy object is set on runtime using the ‘setStatergy’ method.
Figure: - Strategy client code