-
-
Save xhackjp1/3f2519a9b620d6427e1946e681661aa2 to your computer and use it in GitHub Desktop.
State Pattern in Ruby
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 - allow an object to alter its behaviour when its internal state | |
# changes. The object will appear to change its class. | |
# Key idea - introduce an abstract class called SomethingState to represent the | |
# states of the object. Subclasses of the abstract class implement | |
# state-specific behaviour. | |
class Person | |
attr_accessor :state, :name | |
def initialize name, state = PersonStateHappy | |
@state = state.new self | |
@name = name | |
end | |
def state= new_state | |
@state = new_state.new self | |
end | |
def activity | |
"#{@state.listen_to_music} and #{@state.watch_movie}" | |
end | |
end | |
class PersonState | |
def initialize person | |
@person = person | |
end | |
def listen_to_music | |
end | |
def watch_movie | |
end | |
end | |
class PersonStateHappy < PersonState | |
def listen_to_music | |
"#{@person.name} is listening to Girls Just Want to Have Fun by Cyndi Lauper" | |
end | |
def watch_movie | |
"#{@person.name} is watching Toy Story" | |
end | |
end | |
class PersonStateSad < PersonState | |
def listen_to_music | |
"#{@person.name} is listening to Goodbye Blue Sky by Pink Floyd" | |
end | |
def watch_movie | |
"#{@person.name} is watching The Green Mile" | |
end | |
end | |
travis = Person.new("Travis") | |
puts travis.activity | |
travis.state = PersonStateSad | |
puts travis.activity |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment