State Pattern
Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 49 of 57.
The state pattern moves behaviour that depends on an object's current state into separate state objects. The main object, the context, holds one state and forwards calls to it; a state answers and decides which state comes next:
class Red
def next_state
Green.new
end
def to_s
"red"
end
end
class Green
def next_state
Yellow.new
end
def to_s
"green"
end
end
class Yellow
def next_state
Red.new
end
def to_s
"yellow"
end
end
class TrafficLight
def initialize
@state = Red.new
end
def change
@state = @state.next_state
self
end
def to_s
"light is #{@state}"
end
end
light = TrafficLight.new
puts light
puts light.change
puts light.change.changeOutput:
light is red
light is green
light is redWithout the pattern, every method of the context needs a case on a status value, and a new state means editing all of them. With state objects, each state is one class holding its own rules:
# without the pattern
def can_go?
case @status
when :red then false
when :green then true
when :yellow then false
end
end
# with the pattern
def can_go?
@state.can_go?
endStates can refuse an event that does not fit. Here a draft cannot be published directly; it has to go through review first:
class Draft
def submit
Review.new
end
def publish
raise ArgumentError, "cannot publish a draft"
end
def to_s
"draft"
end
end
class Review
def publish
Published.new
end
def to_s
"in review"
end
end
class Published
def to_s
"published"
end
end
state = Draft.new
begin
state.publish
rescue ArgumentError => e
puts e.message
end
state = state.submit
state = state.publish
puts stateOutput:
cannot publish a draft
publishedA shared base class can give every state the default answer, such as refusing every event, so each state only defines the events it accepts:
class State
def submit
raise ArgumentError, "cannot submit #{self}"
end
def approve
raise ArgumentError, "cannot approve #{self}"
end
end
class Review < State
def approve
Published.new
end
endChallenge
EasyComplete the traffic light. The states Red, Green and Yellow each have next_state (red goes to green, green to yellow, yellow to red), can_go? (only green) and to_s (the colour). TrafficLight starts red, change moves to the next state, and status returns red: stop or green: go, asking the state.
The supplied code reads commands change or status and prints the status after each command.
Your code goes in red.rb, green.rb, yellow.rb and traffic_light.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'red'
require_relative 'green'
require_relative 'yellow'
require_relative 'traffic_light'
# Supplied input/output code: keep it as it is
input = []
while (line = gets)
input << line.chomp
end
light = TrafficLight.new
input.each do |cmd|
light.change if cmd == "change"
puts light.status
end
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesInstance VariablesMethods and selfto_s and inspectRecap - Library Card7Polymorphism and Duck Typing
PolymorphismDuck TypingAbstract Methodscase and ClassesRecap - Payment Methods2Accessors and Self
Readers and WritersCustom Settersself in MethodsIdentity and EqualityRecap - Contact List8Special Methods
Equality and hashOperator MethodsIndexing and AppendingCustom CollectionsRecap - Fractions11Project: Library Management
Books and MembersBorrowing Books3Class Methods and Variables
Class MethodsClass Instance VariablesConstantsFactory MethodsRecap - Coupon CodesPractice on your own: Online Ruby compiler