State (objects for states)

These allow an object to alter its behavior when its internal state changes, and it appears as the class changes.

Use state pattern when an object's behavior depends on its state and change at runtime depends on that state.

The diagram depicts both structure of State pattern and a sample implementation; Context class carries states, and Off and On classes implement State interface so that context can use the action on each concrete class's off/on.

Listed are the benefits:

  • Suggest localizes state-specific behavior and partitions behavior for different states (new states and transitions can be added easily by subclass definitions)
  • Makes state transitions explicit
  • State objects are shareable

The impact is, it may make adding a new concrete element difficult.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset