Created
March 26, 2023 00:16
-
-
Save kirillshevch/6a33d37b1f27cbd8e6f07b2d614c2a36 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# 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