Design Patterns #10: State

Design patterns episode 10 – State

Happy Christmas!! Isn’t it a good time to write a post?
Let me start with an apology. In previous post about patterns (composite) I promised to keep that one week/one pattern schedule but as you can see I have failed. But in the meantime I posted something different (one-bytes #1) so I feel forgiven to some extent. Learnt by experience I promise nothing this time. With that being said we can proceed to the next pattern.

Today’s hero is the State. We all know those simple machines which operation model is frequently very simple but closed within exact patterns. For instance the example given in Head First book – a vending machine. It allows only two or three possible interactions (insert coin, get coin back or get the product) and serves one particular purpose (sell products). Its operation model is base on states: the machine can have a coin inserted, can be out of products, etc. So the machine changes its internal state and this change implicates change of behaviour.

DEFINITION
Let’s take a look at the definition and the diagram.

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004) 

In object-oriented programming the above definition is realised by representing these internal states by different implementations of one interface (or inherited from an abstract class). The important thing is the fact the state changes internally. It is not possible to set state from outside. If we go back and think about strategy pattern we will probably see that these two pattern are similar but that closure to changes from outside is what makes them different.


This the diagram depicting the state pattern and similarly to strategy pattern we have encapsulation of behaviour in a separate class: behaviour of Operation() method in context class is encapsulated in state object. It is possible to have multiple states but transitions between them must be done privately. User of state context must not be able to enforce the context to switch state in any other means than normal operation on the context, intended by designer. We don’t have any public method to set the current state from outside. And that is the key to state pattern.

EXAMPLE
I have used a prepaid electricity meter to show the pattern. It can be thought of as a state machine: it can be switch off, switched on but idle, conducting electricity to appliances or be out of credits. Let’s start with the meter interface:

It exposes two properties: one is the credit that the meter is topped-up with, the other is current state of the meter. Both of them are get-only: there is specific method to top-up and the state cannot be set from the outside. Other than that we have methods to turn the meter on/off, start delivering power (for specified number of cycles)  and already mentioned TopUp() method.

The implementation of the meter is slightly more complicated. First we need to equip properties from the interface with setters. Next we need properties for each of the possible states. In this case there are three states: OnStateOffState and MinusState. Other than that we have methods to manipulate with credit and a constructor. This is important: we initialise state instances, set credit to zero and set current state to OffState. The last step is four methods from the IMeter interface. These methods don’t have their own implementation but they call current state object to execute its corresponding operations.
Now the abstraction of state class. In this case I’m using abstract class because I need some not public members, force the inheriting classes to set reference in constructor to the meter the state is going to be used with, and reuse some common pieces of code.

As you can see states will have all the methods that the meter will call in different states. The TopUp() methods has default implementation because it will the same for OnState and MinusState, method ReachZero will be called whenever the meter runs out of credit. It doesn’t need to be virtual because no override will ever be needed.
The last pieces of code would be actual implementations of the sates. Let’s take a look at just one:

As you can see each state provide its own implementation of actions possible for the meter (except for TopUp() which as stated earlier can be shared and in this case it is, but it isn’t in OffState where it is overridden to simply write out on console that the meter is off). Note that some of them changes the state – that’s the core of this pattern: the internal change of state.
Having all the states implemented we can see how it works:

The above would generate output like this:
As you can see we invoked Start() method on one and the same object and we got three different results which all depended on the state in which the object had been, and some of which changed the state of the object. That’s the way how the state pattern works.

Before I prepared this example I had prepared another: a model of vending machine. It is a WPF app. The reason I decided to go for something different was the fact that it had become a bit unclear in the code. Simple console app is much better to illustrate the  pattern. However I did not abandoned the code and you can take a look at this as well. Here’s quick video how it works and the source code you will find at the bottom of this post.

So that’s it for today. Hope you like it 🙂 Before you go please find some useful links below. Enjoy!

Source code – IMeter: TXT file
Source code – Vending machine: GitHub