Skip to content

Instantly share code, notes, and snippets.

@aquateen
Created June 26, 2015 15:47
Show Gist options
  • Save aquateen/8e84dcf4b842944c3d11 to your computer and use it in GitHub Desktop.
Save aquateen/8e84dcf4b842944c3d11 to your computer and use it in GitHub Desktop.
Example of State pattern
# gem install state_pattern
require 'state_pattern'
class Stop < StatePattern::State
def next
sleep 4
transition_to(Go)
end
def color
"Red (four sec...)"
end
end
class Go < StatePattern::State
def next
sleep 2
transition_to(Caution)
end
def color
"Green (two sec...)"
end
end
class Caution < StatePattern::State
def next
sleep 1
transition_to(Stop)
end
def color
"Yellow (one sec...)"
end
end
class TrafficLight
include StatePattern
set_initial_state Stop
end
traffic_light = TrafficLight.new
loop do
puts traffic_light.color
traffic_light.next
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment