Noah Subrin's DEV Blog
Technology for Business minds

State Design Pattern

Print the article

This entry was posted on 11/18/2006 10:22 AM and is filed under Design Patterns.

This week in my SRA-U "Design Patterns in Software Development" class, we discussed the State pattern. I began with a review of State machines in software development. A finite state machine is a model of behavior composed of states, transactions, and actions. A state stores information about the past, i.e. it reflects the input changes from the system start to the present moment. A transition indicates a state change.

So how do we get from states to code?
1) Define the states
2) Create a variable to hold the current states and define values for each state
3) Gather up all the actions that can happen in the system

We worked through a design scenario using a GumballMachine class and its various states - HasQuarter, NoQuarter, SoldOut etc. We discovered that we could create an extensible solution using the State Pattern. Here is our approach:

1) Define a State interface that contains a method for every action in the Gumball machine.
2) Implement a State class for every state of the machine which will be responsible for the behavior of the machine in its respective state.
3) Clean up the conditional code and delegate to the state classes the work to be performed.

To summarize, here is the definition for the State Pattern:
The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

My slide deck is available for download



 

What did you think of this article?




Trackbacks
Trackback specific URL for this entry
  • No trackbacks exist for this entry.
Comments
    • No comments exist for this entry.
Leave a comment

Submitted comments will be subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.