the state design pattern n.
Skip this Video
Loading SlideShow in 5 Seconds..
The State Design Pattern PowerPoint Presentation
Download Presentation
The State Design Pattern

The State Design Pattern

294 Vues Download Presentation
Télécharger la présentation

The State Design Pattern

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. The State Design Pattern A behavioral design pattern. Shivraj Persaud E-mail:

  2. State Design Pattern • Encapsulate states as concrete objects. • Abstract them into an abstract class. • The system contains a reference to an abstract state class, which can be any of the concrete state classes dynamically.

  3. Example – TCPConnection class • A TCPConnection object can be in one of several different states, established, listening or closed. • The behavior of TCPConnection is different in each of these three states.

  4. Abstract state class TCPState TCPConnection Open() Close() Acknowledge() Open() Close() Acknowledge() state->Open() TCPEstablished TCPListen TCPClosed Open() Close() Acknowledge() Open() Close() Acknowledge() Open() Close() Acknowledge()

  5. TCPConnection maintains a state object which is a subclass of TCPState. • When the connection changes state the TCPConnection object changes the state object it uses.

  6. Applicatiblity- when to use the state design pattern • An object’s behavior depends on its state and changes its behavior at run-time. • Operations have large, multipart conditional statements that depend on the object’s state. The State pattern puts each branch of the conditional in a separate class.

  7. UML Diagram of the State Design Pattern

  8. Participants Context (TCPConnection) - defines the interface of interest to clients. - maintains an instance of a ConcreteState subclass that defines the current state.

  9. State (TCPState) - defines an interface for encapsulating the behavior associated with a particular state of the Context. ConreteState Subclasses (TCPEstablished, TCPListen, TCPClosed) - each subclass implements a behavior associated with a state of the Context.

  10. Collaborations Context delegates state-specific requests to the current ConcreteState object. A context may pass itself as an argument to the state object handling the request. This lets the state object access the context if necessary.

  11. Context is the primary interface for clients. Clients can configure a context with State objects. Once a context is configured, its clients don’t have to deal with the State objects directly. Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances.

  12. Consequences It localizes state-specific behavior and partitions behavior for different states. It makes state transitions explicit. State objects can be shared.

  13. Related patterns • Flyweight