- Require the observer library
- Mixin the Observable module to your class which can be observed
- In the class that does the observing, implement the update method
That’s it.
Of course, an example would be nice. Here’s a small one.
require 'observer' # Key step 1
class MyObservableClass
include Observable # Key step 2
def blah
changed # note that our state has changed
notify_observers( 5 )
end
end
class MyObserverClass
def update(new_data) # Key step 3
puts "The new data is #{new_data}"
end
end
watcher = MyObservableClass.new
watcher.add_observer(MyObserverClass.new)
Now, any time that MyObservableClass#blah is called, the observing classes will get notified. In this example, we aren’t dynamically changing the data (in fact, it always stays constant), but I think you can see that if in fact the data DID change, the observers would all get notified of that change.
No comments:
Post a Comment