The State Pattern in Flex 2
I’m currently working on Flex project at Quality Attributes Software that requires the use of a set of tools, similar to Photoshop, to manipulate a drawing canvas. Some examples of tools might be a drag tool, a selection tool, and a zoom tool. I thought to myself, “Ok, simple enough. Throw all the logic into a switch statement inside a generic on click button handler.” So, when a user clicks on a new tool, disable all the functionality from the previous tool, and enable the functionality of the new one. Ugh! This was a complete disaster. What happens when you expose all this logic, is that you run into some very highly coupled code. Meaning that each tool is essentially keeping the state of the other tools. Yuck!
There’s definitely a better way to handle these situations, and that’s by using the state pattern. Essentially, I turned each tool into a state. So when a user clicks on the Selection Tool, the program changes its state to use the functionality of selecting objects on the drawing canvas. I hide all this logic behind an interface, and each tool is represented as a class that implements this interface. If you’d like some code examples of this pattern, William Sanders has a great write up over at Adobe’s Developer Center.