Aircraft Heading Information for IVAO Embedding Cayri on Your Website
Aug 31

Photoshop Tools ThumbI’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.

One Response to “The State Pattern in Flex 2”

  1. Bill Sanders Says:

    Dan

    I’m glad to see that you found a use for the State Design pattern and the kindness to provide a reference! Jonathan Kaye spent hours with me trying to get the concept of a State Machine in my head, and I think that he finally succeeded. We started a blog on ActionScript design patterns at http://www.as3dp.com/ in case you’re interested.

    Kindest regards,
    Bill Sanders

Leave a Reply