Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Summary

Generally speaking, the state of an object depends on the collective value of the object's instance variables. In some cases, an object's state can be a prominent aspect of a class's behavior. This often occurs when an object is modeling a real-world entity whose state is important. In such a situation, complex logic that depends on the object's state may appear in many methods. You can simplify such code by moving state-specific behavior to a hierarchy of state objects. This lets each state class contain the behavior for one state in the domain. It also allows the state classes to correspond directly to states in a state machine.

To handle transitions between states, you can let states retain a context reference that contains a set of states. Alternatively, you can pass around, in state transition calls, the object whose state is changing. Regardless of how you manage state transitions, the STATE pattern simplifies your code by distributing an operation across a collection of classes that represent an object's various states.

  • + Share This
  • 🔖 Save To Your Account