You are on page 1of 10

Design

Design Patterns
Patterns
CE00362-3
CT070-3-3

Behavioral Pattern – State


Introduction & Overview

CT070-3-3 - Design Patterns State Slide 1 (of 12)


Learning Outcomes

At the end of this session, you should be


able to;

– Describe benefits of State pattern


– Recognise and apply State pattern given a
scenario

CT070-3-3 - Design Patterns State Slide 2 (of 12)


What is a State?

• The state of an object depends on the collective


value of the object’s instance variables.
• An object’s state may be a prominent aspect of a
class’s behavior.
• Complex logic that depends on the object’s state
may appear in many methods.

CT070-3-3 - Design Patterns State Slide 4 (of 12)


State Pattern

Intent:
Allow an object to alter its behaviour when its internal state
changes. The object will appear to change its class.
Motivation:
Many programmers have had the experience of creating a
class which performs slightly different computations or
displays different information based on the arguments
passed into the class. This frequently leads to some sort of
switch or if-else statements inside the class that determine
which behavior to carry out. It is this inelegance that the
State pattern seeks to replace.

CT070-3-3 - Design Patterns State Slide 5 (of 12)


Description – State Pattern

Applicability:
Use State pattern should be used
• When an object’s behaviour depends on its
state, and it must change its behaviour at
run-time depending on that state.
• Operation have large, multipart conditional
statements that depend on the object’s
state.
CT070-3-3 - Design Patterns State Slide 6 (of 12)
Definition – State Pattern

Distribute state specific logic across


classes that represent an object’s state.

CT070-3-3 - Design Patterns State Slide 7 (of 12)


State Pattern

Context State

request() handle()

ConcreteStateA ConcreteStateB

handle() handle()

CT070-3-3 - Design Patterns State Slide 9 (of 12)


Summary

In this lecture we have:


• Introduced the State pattern
• Discussed examples that take advantage
of the State pattern

CT070-3-3 - Design Patterns State Slide 10 (of 12)


Question and Answer Session

Q&A

CT070-3-3 - Design Patterns State Slide 11 (of 12)


References

Steven John Metsker, Design Patterns Java


Workbook, Addison Wesley

Erich Gamma et. al., Design Patterns –


Elements of Reusable Object-Oriented
Software, Addison Wesley

CT070-3-3 - Design Patterns State Slide 12 (of 12)

You might also like