State

Alias: Objects for States, Envelope-Letter.

Problem

  • How to treat an object whose behavior is strongly dependent on its internal state, without checking this state at each operation call?

Context

  • The object behavior depends on its state.

  • Operations have large, multipart conditional statements that depend on the object’s state.

Solution

pattern state collaboration
Figure 1. UML Collaboration Diagram

Solution

pattern state collaboration use
Figure 2. UML Class Diagram

Forces

  • State-specific behavior is isolated, increasing maintainability.

  • Replacing a conditional by a delegation may reduce performance.

  • State transition become explicit, increasing testability.

Implementation trade-offs

Who defines the state transitions?
  • The Context: less robust

  • The States: the context must provide an appropriate interface and the states must know the context.

How to create and destroy states?
  1. When the context is created.

  2. Later (lazy instantiation).

  3. Dynamic inheritance may be used in Self

Implementation trade-offs (Cont.)

  • State sub-instances may be shared by several contexts, if they do not contain properties.

Author and Date

  • The State pattern is part of the GoF Catalog.

  • It was applied to TCP connection protocols [Johnson and Zweig 91] and to graphical editors such as HotDraw [Johnson 92] and Unidraw [Vlissides and Linton 90].

State