Skip to content

Commit

Permalink
Add state pattern
Browse files Browse the repository at this point in the history
closes #10
  • Loading branch information
veelenga committed Oct 14, 2017
1 parent a206d60 commit 5a634df
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -14,6 +14,7 @@ The goal is to have a set of [GOF patterns](http://www.blackwasp.co.uk/gofpatter
- [Iterator](behavioral/iterator.cr)
- [Memento](behavioral/memento.cr)
- [Observer](behavioral/observer.cr)
- [State](behavioral/state.cr)
- [Strategy](behavioral/strategy.cr)
- [Template](behavioral/template.cr)
- [Visitor](behavioral/visitor.cr)
Expand Down
38 changes: 38 additions & 0 deletions behavioral/state.cr
@@ -0,0 +1,38 @@
# Defines a manner for controlling communication between classes or entities.
# The state pattern is used to alter the behaviour of an object as its internal
# state changes.

class GameContext
property state : State

def initialize(@state)
end

def toggle
@state.handle(self)
end
end

abstract class State
abstract def handle(context : GameContext)
end

class PauseState < State
def handle(context : GameContext)
puts "Pause -> Play"
context.state = PlayState.new
end
end

class PlayState < State
def handle(context : GameContext)
puts "Play -> Pause"
context.state = PauseState.new
end
end

initial_state = PlayState.new
context = GameContext.new initial_state

context.toggle # Play -> Pause
context.toggle # Pause -> Play

0 comments on commit 5a634df

Please sign in to comment.