Created
June 26, 2015 15:47
-
-
Save aquateen/8e84dcf4b842944c3d11 to your computer and use it in GitHub Desktop.
Example of State pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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