diff --git a/README.md b/README.md index 9cd9cb3..f393bb9 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/behavioral/state.cr b/behavioral/state.cr new file mode 100644 index 0000000..bdbec03 --- /dev/null +++ b/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