The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.

Slides:



Advertisements
Similar presentations
GoF State Pattern Aaron Jacobs State(305) Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Advertisements

Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Matt Klein 7/6/2009.  Behavioral Pattern  Intent  Allow an object to alter its behavior when its internal state changes. The object will appear to.
Reza Gorgan Mohammadi AmirKabir University of Technology, Department of Computer Engineering & Information Technology Advanced design.
. Plab – Tirgul 12 Design Patterns. Design Patterns u The De-Facto Book on Design Patterns:
BehavioralCmpE196G1 Behavioral Patterns Chain of Responsibility (requests through a chain of candidates) Command (encapsulates a request) Interpreter (grammar.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
C++ fundamentals.
Object-Oriented Analysis and Design
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
Design Patterns Discussion of pages: xi-11 Sections: Preface, Forward, Chapter
BDP Behavioral Pattern. BDP-2 Behavioral Patters Concerned with algorithms & assignment of responsibilities Patterns of Communication between Objects.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Practical Object-Oriented Design with UML 2e Slide 1/1 ©The McGraw-Hill Companies, 2004 PRACTICAL OBJECT-ORIENTED DESIGN WITH UML 2e Chapter 2: Modelling.
Design Patterns.
Software Design Refinement Using Design Patterns Instructor: Dr. Hany H. Ammar Dept. of Computer Science and Electrical Engineering, WVU.
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Decorator, Strategy, State Patterns.
Patterns and Reuse. Patterns Reuse of Analysis and Design.
Strategy Design Patterns CS 590L - Sushil Puradkar.
3-1 State Design Pattern C Sc 335 Rick Mercer. State Design Pattern State is one of the Behavioral patterns It is similar to Strategy Allows an object.
Object Oriented Design David Talby. Welcome! n Introduction n UML u Use Case Diagrams u Interaction Diagrams u Class Diagrams n Design Patterns u Composite.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Behavioral Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
© 2006 Pearson EducationDesign Patterns1 of 20 A Final Example: A Traffic Light Let’s model a traffic light! – here’s the spec: Have a column of two circles.
Design Patterns Introduction
The Visitor Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Interpreter Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Stéphane Ducasse 1 Strategy.
The Facade Pattern (Structural) ©SoftMoore ConsultingSlide 1.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
STATE PATTERN Presented by Bharavi Mishra Bharavi Mishraise
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
The Flyweight Pattern (Structural) ©SoftMoore ConsultingSlide 1.
The Singleton Pattern (Creational)
The Proxy Pattern (Structural) ©SoftMoore ConsultingSlide 1.
The Memento Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
Overview of Creational Patterns ©SoftMoore ConsultingSlide 1.
The Abstract Factory Pattern (Creational) ©SoftMoore ConsultingSlide 1.
The Chain of Responsibility Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The State Design Pattern A behavioral design pattern. Shivraj Persaud
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Command Pattern. Intent encapsulate a request as an object  can parameterize clients with different requests, queue or log requests, support undoable.
Design Patterns: MORE Examples
Design Patterns: Brief Examples
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Software Design Patterns
Factory Patterns 1.
Introduction to Design Patterns
Behavioral Design Patterns
Software Design and Architecture
State pattern – A logical ‘Finite State Machine’
object oriented Principles of software design
State Design Pattern 1.
Introduction to Behavioral Patterns (2)
Context Objects Evolution of object behavior Behavioral patterns
Lecture 8 Evolution of object behavior Behavioral patterns
Strategy Design Pattern
Object Oriented Design
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Presentation transcript:

The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1

Background The state of an object is an abstraction of its attribute values and links. Sets of values are grouped together into a state according to properties that affect gross behavior of the object. All objects of a class with the same state react in the same general way to an event; however, objects in different states may react differently to the same event. Sometimes the conceptual state of an object can be captured in a single attribute; e.g., using an integer value or the value of an enumerated type. ©SoftMoore ConsultingSlide 2

Background (continued) State-dependent behavior: The effect of calling a method depends not only on the method being called and the parameters passed to it, but also on the state of the object at the time the method is called. Most objects exhibit some state-dependent behavior. Some objects exhibit complex state-dependent behavior. ©SoftMoore ConsultingSlide 3

The behavior for a simple garage door opener could be described by the following state diagram: One way to implement a controller for the garage door opener would be to use conditional statements. Motivating Example (David Bernstein, James Madison University) ©SoftMoore ConsultingSlide 4 Open Closed close open lock EnteringLocked start unlock error unlock

public class Controller { private int state; // states private static final int ENTERING = 0; private static final int CLOSED = 1; private static final int LOCKED = 2; private static final int OPENED = 3; // actions private static final int ENTER = 0; private static final int CLOSE = 1; private static final int LOCK = 2; private static final int OPEN = 3; Motivating Example (continued) ©SoftMoore ConsultingSlide 5

public Controller() { setState(CLOSED); } private void setState(int state) { this.state = state; } Motivating Example (continued) ©SoftMoore ConsultingSlide 6

public void onChange(int action) { if (action == CLOSE)) { if (state == OPENED) { close(); setState(CLOSED); } if (action == LOCK) { if (state == CLOSED) { lock(); setState(LOCKED); }... Motivating Example (continued) ©SoftMoore ConsultingSlide 7

This implementation is difficult to understand and maintain. Consider the problem of adding a new state. The State design pattern provides an alternative way to implement the controller. Motivating Example (continued) ©SoftMoore ConsultingSlide 8

State Pattern Intent: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. Also Known As: Objects for States Slide 9©SoftMoore Consulting

State Pattern (continued) Applicability: Use the State pattern in either of the following cases: An object’s behavior depends on its state, and it must change its behavior at run-time depending on that state. Operations have large, multipart conditional statements that depend on the object’s state, and the state can be represented by one or more enumerated constants. Often, several operations will contain the same conditional structure. The State pattern puts each branch of the conditional in a separate class. ©SoftMoore ConsultingSlide 10

State Pattern (continued) ©SoftMoore ConsultingSlide 11 State handle() ConcreteStateB handle() Structure ConcreteStateC handle() ConcreteStateA handle() Context request() state state.handle()

State Pattern (continued) Participants Context –defines the interface of interest to clients. –maintains an instance of a ConcreteState subclass that defines the current state. State –defines an interface for encapsulating the behavior associated with a particular state of the Context. ConcreteState subclasses –each subclass implements a behavior associated with a state of the Context. ©SoftMoore ConsultingSlide 12

State Pattern (continued) Collaborations Context delegates state-specific requests to the current ConcreteState object. A context may pass itself as a parameter to the State object handling the request – allows the State object to access the context. Context provides the primary interface to clients. Clients can configure a context with State objects, but once a context is configured, its clients don’t have to deal with State objects directly. ©SoftMoore ConsultingSlide 13

State Pattern (continued) Collaborations (continued) Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances. ©SoftMoore ConsultingSlide 14

State Pattern (continued) Consequences: The State pattern Localizes state-specific behavior and partitions behavior for different states. Since all state-specific code lives in a State subclass, new states and transitions can be added easily by defining new subclasses. The alternative would require modification to several methods to add new braches to conditional statements. Makes state transitions explicit. State transitions are achieved by one variable, the Context object’s state variable. ©SoftMoore ConsultingSlide 15

State Pattern (continued) Consequences (continued) Allows state objects to be shared. State objects can be shared if they have no instance variables; i.e., if the state they represent is encoded entirely in their methods. In this case, the state objects are essentially flyweights with no intrinsic state, only behavior. ©SoftMoore ConsultingSlide 16

State Pattern (continued) Implementation Who defines the State transitions. If the criteria for state transitions are fixed, then they can be implemented entirely in the Context. Alternatively, the State subclasses can specify when to make the transition and the appropriate successor state. A table-based alternative. It may be possible to use a transition table to map inputs to successor states. This approach converts conditional code to a table look-up. ©SoftMoore ConsultingSlide 17

State Pattern (continued) Implementation (continued) Creating and destroying state objects. Should state objects be created only when they are needed and destroyed thereafter, or should all state objects be created ahead of time and never destroyed? The first alternative might be preferable when contexts change state infrequently. The second alternative pays the costs for instantiation up-front. Using dynamic inheritance. Some programming languages effectively allow an object to change its class at run-time. ©SoftMoore ConsultingSlide 18

Motivating Example Revisited public interface State { public void enter(); public void close(); public void lock(); public void open(); } ©SoftMoore ConsultingSlide 19

Motivating Example Revisited (continued) public class Closed implements State { private Controller controller; public Closed(Controller controller) { this.controller = controller; } public void enter() { // ignore } public void close() { // ignore } ©SoftMoore ConsultingSlide 20

Motivating Example Revisited (continued) public void lock() {... // code to lock the door controller.changeState(getState(LOCKED); } public void open() {... // code to open the door controller.changeState(getState(OPENED)); } ©SoftMoore ConsultingSlide 21

Guidelines on Using the State Pattern The state pattern is most beneficial when a class has several methods with conditional/multiway branches that depend on the state, or when it has a single such method that is complicated and difficult to understand. If a class has only one method with a conditional/multiway branch that depends on the state, and if that method has a simple, coherent, and regular structure, then the benefits obtained by using the state pattern might be minimal. ©SoftMoore ConsultingSlide 22

Related Patterns The Flyweight pattern explains when and how State objects can be shared. State objects are often Singletons. State and Strategy have similar UML diagrams, but they differ in their intent. –A Strategy encapsulates an algorithm, whereas a State encapsulates state information and state-dependent behavior. –Clients often select the appropriate Strategy but not the State. (But Clients can sometimes select the initial state.) –Both State and Strategy are examples of composition with delegation. ©SoftMoore ConsultingSlide 23

References State pattern (Wikipedia) State Design Pattern (SourceMaking) How to implement state-dependent behavior: Doing the State pattern in Java (Eric Armstrong, JavaWorld) state-dependent-behavior.html The State Pattern (by David Bernstein, JMU) ©SoftMoore ConsultingSlide 24