Menu
Coddy logo textTech

Observer Pattern

Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 44 of 57.

The observer pattern lets objects subscribe to changes of another object, the subject. The subject keeps a list of observers and notifies each one when something happens, without knowing what they do with it:

class Thermometer
  def initialize
    @observers = []
  end

  def subscribe(observer)
    @observers << observer
  end

  def temperature=(value)
    @temperature = value
    @observers.each { |o| o.update(value) }
  end
end

class Display
  def update(value)
    puts "display: #{value} C"
  end
end

class Alarm
  def update(value)
    puts "alarm: too hot!" if value > 30
  end
end

t = Thermometer.new
t.subscribe(Display.new)
t.subscribe(Alarm.new)
t.temperature = 25
t.temperature = 35

Output:

display: 25 C
display: 35 C
alarm: too hot!

The observers only need an update method: duck typing. Each can be a completely different class, and new observers can be added without changing the subject:

class Logger2
  def update(value)
    @history = (@history || []) << value
  end
end

thermometer.subscribe(Logger2.new)   # the subject is unchanged

Observers can also be blocks. The subject stores them as procs and calls them with call. unsubscribe removes an observer again:

class Button
  def initialize
    @handlers = []
  end

  def on_click(&handler)
    @handlers << handler
    handler
  end

  def unsubscribe(handler)
    @handlers.delete(handler)
  end

  def click
    @handlers.map { |h| h.call("clicked") }
  end
end

b = Button.new
b.on_click { |e| "A got #{e}" }
second = b.on_click { |e| "B got #{e}" }
p b.click
b.unsubscribe(second)
p b.click

Output:

["A got clicked", "B got clicked"]
["A got clicked"]

The subject decides what to send. Passing the subject itself lets an observer read what it needs; passing an event name lets one observer react to several kinds of changes:

@observers.each { |o| o.update(self) }          # observer reads subject.price
@observers.each { |o| o.update(:sold_out, self) }  # observer checks the event
challenge icon

Challenge

Easy

Complete the subject Stock and two observers. Stock.new(symbol) has subscribe(observer) and update_price(value), which stores the price and returns the non-nil replies of update(stock) on every observer, in subscription order. PriceDisplay#update returns AAPL now 12.50. PriceAlert.new(limit) returns ALERT AAPL above 100.00 when the price rises above the limit from at or below it, and nil otherwise.

The first input line is the symbol and the alert limit. The supplied code subscribes a display and an alert, then prints the replies for every set price line.

Your code goes in stock.rb, price_display.rb and price_alert.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'stock'
require_relative 'price_display'
require_relative 'price_alert'

# Supplied input/output code: keep it as it is
input = []
while (line = gets)
  input << line.chomp
end
symbol, limit = input[0].split
stock = Stock.new(symbol)
stock.subscribe(PriceDisplay.new)
stock.subscribe(PriceAlert.new(limit.to_f))
input.drop(1).each do |line|
  stock.update_price(line.split[1].to_f).each { |reply| puts reply }
end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online Ruby compiler