Skip to content

Instantly share code, notes, and snippets.

@kirillshevch
Created March 26, 2023 00:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirillshevch/6a33d37b1f27cbd8e6f07b2d614c2a36 to your computer and use it in GitHub Desktop.
Save kirillshevch/6a33d37b1f27cbd8e6f07b2d614c2a36 to your computer and use it in GitHub Desktop.
# State interface
class TrafficLightState
def change_state(_traffic_light)
raise 'This method should be implemented in a subclass'
end
def display_color
raise 'This method should be implemented in a subclass'
end
end
# Concrete states
class RedState < TrafficLightState
def change_state(traffic_light)
traffic_light.state = YellowState.new
end
def display_color
'Red'
end
end
class GreenState < TrafficLightState
def change_state(traffic_light)
traffic_light.state = YellowState.new
end
def display_color
'Green'
end
end
class YellowState < TrafficLightState
def change_state(traffic_light)
if traffic_light.previous_state.is_a?(RedState)
traffic_light.state = GreenState.new
else
traffic_light.state = RedState.new
end
end
def display_color
'Yellow'
end
end
# Context
class TrafficLight
attr_accessor :state, :previous_state
def initialize(state = GreenState.new)
@state = state
@previous_state = state
end
def change_state
@previous_state = @state
@state.change_state(self)
end
def display_color
@state.display_color
end
end
# Usage
traffic_light = TrafficLight.new
puts traffic_light.display_color
traffic_light.change_state
puts traffic_light.display_color
traffic_light.change_state
puts traffic_light.display_color
traffic_light.change_state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment