Definition-Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
//UML Class Diagram
When to use?
• Suppose an object is always in one of several
known states
• The state an object is in determines the behavior
of several methods
• Could use if/case statements in each method
Compared to Strategy Pattern
Strategy Pattern typically configures context classes with a behavior or algorithm. But State Pattern allows a context to change its behavior as the state of the context changes.
Watch out: Using the State Pattern will typically result in a greater number of classes in your designed.
Notes
• Can use singletons for instances of each state class
– State objects don’t encapsulate state, so can be shared
• Easy to add new states
– New states can extend other states
• Override only selected functions
Example:
//Class Diagram
//Code
//Main.java







































































































































































//if u find anything interesting, pls contact with me.QQ:95491590