Skip to content

Instantly share code, notes, and snippets.

@travisjeffery
Created March 11, 2012 01:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save travisjeffery/2014395 to your computer and use it in GitHub Desktop.
Save travisjeffery/2014395 to your computer and use it in GitHub Desktop.
State Pattern in Ruby
# 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