Thursday, December 10, 2015

Head First Design Pattern Ch10: State Pattern

State pattern is about keeping state, It is very  similar to strategy pattern we will talk about that later.

we will start by an example to understand the problem that state patters solves

lets take an example of a Gum Ball machine. the gumball machine is a state machine which could have the one of the following states

you can represent these states in java by using final static vairables

the gumball machine has the following actions

now if you want to write code to implement this you will write something like this

as you can see a lot of else if, and if any change happens then we should change in many places.

the solution is to use the state pattern 

as you can see for each state you have a class and you do the implementation in that class.

as you can see above, an implementation for one of the states, also you can see that the state has a reference to the GumballMachine, and in insertQuarter() we change the state to something else.

as you can see above in GumballMachine, we have an instance of each state and we actually pass (this) to all these states.

Strategy Pattern vs State Pattern
in general they are similar, however we use them for different things, State pattern is like a state machines, so you define the way you move from one state to another. sure you can change the behaviour in Strategy Pattern but you change it in a different way.

No comments:

Post a Comment