Pattern · Core

State

Let an object change its behaviour when its internal state changes — so it appears to switch class — by delegating to a State object instead of a wall of if/else.

Asked atAmazonUberAtlassian
step 1 / 7
1/2A state object per state
current
Document
- state: State
+ publish()
+ edit()
«interface»
State
+ publish(doc)
+ edit(doc)
Draft
+ publish()
Moderation
+ publish()
Published
+ publish()
A state object per state
1interface State { void publish(Document d); }
2class Draft implements State { ... }
3class Moderation implements State { ... }
4class Published implements State { ... }
5class Document { State state; void publish(){ state.publish(this); } }
State
Documentdelegates to state

The Document is the Context. It holds its CURRENT State and delegates every call — publish(), edit() — straight to it.