The observer pattern is a software design pattern in which an object (called subject
) maintains a list of its dependents (called observers
), and notifies them automatically of any state changes, usually by calling one of their methods.
Ruby provides a simple mechanism to implement the Observer design pattern. The module Observable
provides the logic to notify the subscriber of any changes in the Observable object.
For this to work, the observable has to assert it has changed and notify the observers.
Objects observing have to implement an update()
method, which will be the callback for the Observer.
Let's implement a small chat, where users can subscribe to users and when one of them write something, the subscribers get notified.
require "observer"
class Moderator
include Observable
def initialize(name)
@name = name
end
def write
message = "Computer says: No"
changed
notify_observers(message)
end
end
class Warner
def initialize(moderator, limit)
@limit = limit
moderator.add_observer(self)
end
end
class Subscriber < Warner
def update(message)
puts "#{message}"
end
end
moderator = Moderator.new("Rupert")
Subscriber.new(moderator, 1)
moderator.write
moderator.write
Producing the following output:
# Computer says: No
# Computer says: No
We've triggered the method write
at the Moderator class twice, notifying its subscribers, in this case just one.
The more subscribers we add the more the changes will propagate.