STATE PATTERN Ben Verducci WHAT IS THE STATE
STATE PATTERN Ben Verducci
WHAT IS THE STATE PATTERN? AND WHY SHOULD I CARE? • Problem – An object’s behavior depends on its current internal state, want to perform the correct operations for correct state • One solution: write many conditional statements for each operation that the object can perform (this can get messy) • (sometimes) Better Solution – State Pattern • Allows for a class to behave differently under different circumstances (states) at runtime
GENERALIZED UML DIAGRAM Invokes State. handle()
PARTS OF THE STATE PATTERN • Context • Contains state object • Indicates the current state • State • Interface for the concrete states • Concrete States • Defines each state that the object can be in (and functionality) • Can be any number of states
WHEN SHOULD I USE THE STATE PATTERN? • When an objects behavior depends on its state, and that behavior must change at runtime depending on the current state • When you have complicated conditional structures in several different operations that depend on an objects state
ADVANTAGES AND DISADVANTAGES • Advantages: • Can save you from having to write many conditionals multiple times (DRY) • Makes it easier to make changes later • Additions, deletions, and edits • Simplifies and localizes conditions • Conditional logic isn’t spread out (if statements everywhere) • More explicitly indicates state • Disadvantages: • Adds more classes • Can add unnecessary design complexity depending on use
EXAMPLE • Phone notifications • Three states: Ringer on, vibrate, and silent mode • State pattern would actually add complexity in such a small example, but what if we needed to add several more functionalities that relied on the ringer state?
HOW IS THIS DIFFERENT FROM STRATEGY? • Similar design patterns, solve different problems • State pattern deals with what state an object is in, rather than how a certain task should be accomplished • State pattern involves changes to the internal state at runtime • State often changes when an operation is performed
- Slides: 8