The State Pattern gives us an opportunity to return different results from a class, depending on its state. With the State Pattern we can call a method to a class, which then checks its state to see which result to return. In the pattern, we have a “Context”, a “State”, and multiple “ConcreteState”. When using the pattern, we call the “State” class, which checks its current state, to return the correct result.
A man can have his good and bad days. Some days he will respond kindly, while other days he will avoid contact. If we greet him with a “Goodmorning”, he might respond with a “Goodmorning to you, too” or “Its not a good morning”, depending on his mood. With the State Pattern, we are able to call a method to a class and get different responds.
A vending machine offers a lot of different goodies in exchange for money. You can buy cola, chocolate and all sorts of things. But what if there are no more cola? And the chocolate stock is empty? Then no matter how much money you feed the machine, it wont give you anything, except your money back. With the State Pattern we can set the ConcreteState of the vending machine to vary upon the number of goods, sending a status to customers. The first status we call “Ready” and the second status “Empty”. When we order a cola and the machine’s state is on “Ready” the vending machine returns a cola. If we order a cola and the machine’s state is on “Empty”, it just returns our money. Same method – different response.