Upload
others
View
9
Download
0
Embed Size (px)
Citation preview
Example Elevator design
Pieter van den Hombergh
Fontys Hogeschool voor Techniek en Logistiek
September 30, 2016
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Content
Example: Lift SystemVarious ways to implementstate behavior
State patternState Behavior Notations
Notation
State implementationsTraditional hand codingExplicit State VariableState ObjectsDecoupling from Context
HOM/FHTenL Example Elevator design September 30, 2016 2/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State
Classification: BehavioralIntent: Allow an object to alter its behavior when itsinternal state changes. This can be used to make anobject appear as if it changed its class.Motivation:
In reactive systems operations (events) have a differentresult in different states of an objectIn OO design often the behavior of a class isconveniently expressed in terms of state charts. Onewould like to implement the behavior straightforwardlyfrom these state charts. State charts are rather difficultto make. One does not want to throw them away whenimplementing classes.If one has no concurrency primitives offered in theprogramming language or OS and it is necessary tomake a sequential program one can “fake” concurrencyusing the state pattern
HOM/FHTenL Example Elevator design September 30, 2016 3/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Elevator example
Class LiftCage:Events:
visitarriveAtdoorIsclosed
LightedButton
floor
clear() press()
Motor
destination floor
raise() lower() justAbove() justBelow() setDestination()
LiftCage
currentFloor
visit(floor) arriveAt(floor) doorIsClosed()
floor : int floor : int
floorRequestButton
theMotor
Door
closureTimeOut
open() close() stopClosing()
theDoor
States:Cruising: the lift cage is moving towards somedestination floorDoorOpen: the lift cage is at a floor with the door openWaiting: the lift cage has no pending requests andwaits at a floor with the doors closed
HOM/FHTenL Example Elevator design September 30, 2016 4/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State
Participants:Context:
defines the interface of interest to clients.maintains an instance of a ConcreteState subclass thatdefines the current state.
State:defines an interface for encapsulating the behaviorassociated with a particular state of the context
ConcreteState:each subclass implements behavior associated with astate of the context.
HOM/FHTenL Example Elevator design September 30, 2016 5/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State
Applicability:An object behavior depends on its state. This is oftenthe case in reactive systems and is expressed in statecharts of objects.Operations may have large multi-part conditionalstatements that involve the objects state. The statepattern puts each branch of the conditional in aseparate subclass of the state abstraction.It is expected that the behavior of a class, in particularthe number of states, may change later or is likely tochange by sub-classing the context.
Prevents coupling:No hard-coded operations in contextAlgorithms can be changed by changing stateimplementationEasier to modify class according to updated design(state chart).
HOM/FHTenL Example Elevator design September 30, 2016 6/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State
Consequences:It localizes state-specific behavior.It makes transitions explicit.State objects can be shared between different contexts.( If the state itself is state-less).It may help to implement behavior expressed in complexstate charts.It requires either that the context’s state variables arepart of the concrete state objects, or that the concretestates have access to the state variables of the context.To avoid breaking encapsulation such state variablesmust be shared using C++ “friend”-like mechanisms. InJava this can be achieved in package private classes.
HOM/FHTenL Example Elevator design September 30, 2016 7/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
The GoF State PatternThe state pattern uses an interface that defines the “events”that are to be accepted and uses a differentclass object to define the reaction in any of the defined states.
Advantages:The states can be defined in separate files andseparately tested.On level of checking is dropped.Default reactions (e.q. logging of events) can be reused.
HOM/FHTenL Example Elevator design September 30, 2016 8/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State pattern example, state diagram
HOM/FHTenL Example Elevator design September 30, 2016 9/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State pattern example, class diagram for statepattern
HOM/FHTenL Example Elevator design September 30, 2016 10/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Implementation remarksNote that the state class and its subclasses do/should nothave any attributes. This is typical for the state pattern. Astate IS a state and does NOT have state (i.e. attributes).
The operations the state can execute are defined in thecontext (the door in the example). A typical Javaimplementation (c|w)ould use inner classes for the states(with the potential problem of one big state machine file).
The C++ solution would be to pass the context as aparameter to the event methods, thereby preventing to haveto pass the context as a attribute for the constructor. Thiscan also be used in Java of course, although it would forceyou to increase the visibility of the implementation, therebymaking the implementation more brittle.
HOM/FHTenL Example Elevator design September 30, 2016 11/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State behaviorWe assume that the desired state behavior is documented inthe UML state diagram notation.
Dependent on the tool that you use, it is possible toderive the necessary transition information from such adiagram.This information can be used to create animplementation.There are numerous ways to derive the implementationfrom the notation.
HOM/FHTenL Example Elevator design September 30, 2016 12/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State behavior notation aspectAll the information that is possible and potentially availablein the the UML state diagram can be notated in textual oreven tabular form.
The modern UML tools support a XML based format calledXMI (for XML Meta-data Interchange) that may containstate model information.
In all cases, a correct drawing of your state model can beused to derive a notation that can be used for automaticcode generation.
HOM/FHTenL Example Elevator design September 30, 2016 13/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
A textual notationNotation: (by the way: this is not XML)�state�;�event�[�guard�]/{�action list�};�newstate�
where the guard is optional.
For the state we have the notation:@�name�;ENTRY �entry actions�;EXIT
�exit actions�;�initial state�;�history state�
For nested state we use the notation �parent�.�child�
Examples:S1;e1[g1]/a1();S3.S31
@VISITFLOOR;ENTRY -; EXIT -; VISITFLOOR.OPENING
HOM/FHTenL Example Elevator design September 30, 2016 14/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Nested switch statementTraditionally the state of can be implemented using a doublynested switch statement.
Advantages
Simple to understand.Useable in both OO andnon OO languages
Disadvantages
Only maintainable in oneever growing file.
Variations:Top level is state, nested are the events.Top level are events, nested are the states.
HOM/FHTenL Example Elevator design September 30, 2016 15/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State − > event example in C++void StateMachine :: handleButton ( Button b){
switch (state) {case S1:
switch (b.type ){// ...
case UP:// ...break
}case S2:
switch (b.type ){// ...
case DOWN:// ...break
}break ;
}}
HOM/FHTenL Example Elevator design September 30, 2016 16/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Event− > state example in C++void StateMachine :: handleButton ( Button b){
switch (b.type ){case UP:
switch (state) {// ...
case S1:// ...break
}case DOWN:
switch (state ){// ...
case S2:// ...break
}break ;
}}
HOM/FHTenL Example Elevator design September 30, 2016 17/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Discussion of alternativesThe event − > state is advantageous in the case thatdifferent event are encoded as different method calls. Thenall reaction to this event is specified in one method body.
HOM/FHTenL Example Elevator design September 30, 2016 18/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Example: State model of the Elevator CageNote: this state model is simplified.
State chartIn each of the states the response to events is different
DoorOpen entry/arrive()
visit( request ) [ request.floor!=floor ]/depart()
[ f==floor ][ f!=floor ] / floor=f
visit( request )[ if(request==queue.first())]/depart()
atFloor( f )
[ else ] / depart()
[ queue.isEmpty() ]
doorIsClosed()
Cruising
Waiting
Stopped
HOM/FHTenL Example Elevator design September 30, 2016 19/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Implementing Complex State Behavior
Attempt 0: Keeping implicit state variables. Implicitemeans here: derive from inputs and state of outputs,like is motor moving
Disadvantage: relation to state diagrams obscure, hardto maintain.
Attempt 1: Introducing explicit state variablesDisadvantages: complex conditionals, still not easy tomaintain
HOM/FHTenL Example Elevator design September 30, 2016 20/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Explicit state variable codeAttempt 1 implementation:
c l a s s L i f t C a g e {p r o t e c t e d i n t c u r e n t F l o o r = 0 ;p r o t e c t e d f i n a l i n t DoorOpen = 0 ;p r o t e c t e d f i n a l i n t Wait ing = 1 ;p r o t e c t e d f i n a l i n t C r u i s i n g = 2 ;// c u r r e n t s t a t ep r o t e c t e d i n t s t a t e = Wait ing ;p u b l i c L i f t C a g e ( ) {
// . . .}p u b l i c v o i d v i s i t ( i n t f l o o r ) {
i f ( s t a t e==C r u i s i n g ) { . . .}e l s e i f ( s t a t e==Wait ing ) { . . .}e l s e i f ( s t a t e==DoorOpen ) { . . .}
}
p u b l i c v o i d d o o r I s C l o s e d ( ) {i f ( s t a t e==DoorOpen ) {
// . . .}
}p u b l i c v o i d a t F l o o r ( i n t f l o o r ){
i f ( s t a t e==C r u i s i n g&& f l o o r==c u r r e n t F l o o r ){
// . . .}
}}
Attempt 1: Introducing explicit state variablesDisadvantages: complex conditionals, still not easy tomaintain
HOM/FHTenL Example Elevator design September 30, 2016 21/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Implementing Complex State Behavior
Attempt 2: Introducing explicit state objects (cont’d)
c l a s s L i f t C a g e {// to be a c c e s s e d by s t a t e s :p u b l i c f i n a l S t a t e doorOpen
= new DoorOpen ( t h i s ) ;p u b l i c f i n a l S t a t e w a i t i n g
= new Wait ing ( t h i s ) ;p u b l i c f i n a l S t a t e c r u i s i n g
= new C r u i s i n g ( t h i s ) ;p r o t e c t e d S t a t e s t a t e=w a i t i n g ;p r o t e c t e d i n t c u r r e n t F l o o r =0;p u b l i c i n t g e t F l o o r ( ) {
r e t u r n c u r r e n t F l o o r ( ) ;}p u b l i c v o i d s e t F l o o r ( i n t f l o o r ) {
c u r r e n t F l o o r = f l o o r ;}
p u b l i c v o i d s e t S t a t e ( S t a t e s ) {s t a t e=s ;
}
// to be c a l l e d by c l i e n t s :p u b l i c v o i d v i s i t ( i n t f l o o r ) {
s t a t e . v i s i t ( f l o o r ) ;}p u b l i c v o i d d o o r I s C l o s e d ( ) {
s t a t e . d o o r I s C l o s e d ( ) ;}p u b l i c v o i d a t F l o o r ( i n t f l o o r ){
s t a t e . a t F l o o r ( f l o o r ) ;}
}
HOM/FHTenL Example Elevator design September 30, 2016 22/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
Implementing Complex State Behavior
Attempt 2: Introducing explicit state objects
i n t e r f a c e S t a t e {v o i d v i s i t ( i n t f l o o r ) ;v o i d d o o r I s C l o s e d ( ) ;v o i d a t F l o o r ( i n t f l o o r ) ;
}
c l a s s C r u i s i n g implements S t a t e {p r o t e c t e d L i f t C a g e c o n t e x t ;p u b l i c C r u i s i n g ( L i f t C a g e c ) { c o n t e x t = c ; }// . . . .p u b l i c v o i d a t F l o o r ( i n t f l o o r ) {
i f ( f l o o r== c o n t e x t . g e t F l o o r ( ) ) {c o n t e x t . s e t S t a t e ( c o n t e x t . doorOpen ) ;
}}
}
HOM/FHTenL Example Elevator design September 30, 2016 23/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State
State Pattern Structure
ConcreteStateA
Handle()
ConcreteStateB
Handle()
Context
Request() o
State
Handle()
state
state->Handle()
Note: Often, the state needs some resources of the context,saying that most implementations will pass the context as inhandle(Context ctx) method.
HOM/FHTenL Example Elevator design September 30, 2016 24/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State-less State
In attempt 2, each state constructor is bound (coupling,dependency) to one context.A better approach would be to pass the contextreference with each method call. This allows state-lessstates, making it possible to share state objects betweenmachines. These state objects could then be createdonce and reused, making the object resource usageminimal.Consequences:
Pass the context object to each state method as invoid atFloor(LiftCage cage, int floor ).Implement method setNewState(State ns) inContextTo top it all off, in setNewState(State ns) callstate.exitState() and state.enterState(), toget exit and entry behaviour almost for free.
HOM/FHTenL Example Elevator design September 30, 2016 25/26
Example Elevatordesign
HOM
Example: LiftSystem
Various ways toimplement statebehaviorState pattern
State BehaviorNotationsNotation
StateimplementationsTraditional hand coding
Explicit State Variable
State Objects
Decoupling from Context
State change in contextp u b l i c S t a t e changeSta te ( S t a t e newState ){
S t a t e p r e v i o u s = c u r r e n t S t a t e ;p r e v i o u s . e x i t ( ) ;c u r r e n t S t a t e= newState ;c u r r e n t S t a t e . e n t e r ( ) ;r e t u r n p r e v i o u s ;
}
HOM/FHTenL Example Elevator design September 30, 2016 26/26
Example: Lift SystemVarious ways to implement state behaviorState pattern
State Behavior NotationsNotation
State implementationsTraditional hand codingExplicit State VariableState ObjectsDecoupling from Context