This class enables an object to broadcast a notification that an event occurred to other objects, without having any knowledge of the objects that it is broadcasting to. An object posts a notification (identified by a string and possibly an associated object) to a NotificationCenter (generally the default one). The NotificationCenter then takes care of sending the notification to all of the objects that have registered to receive it.
The purpose of the optional associated object is generally to pass the object posting the notification to the receivers, so that the receivers can query the posting object for more information about the event.
Multiple notification centers may be created (as usual, with the
new
method), but there is one
NotificationCenter available by default through the method
NotificationCenter.instance
. This is a weak form of the Singleton
design pattern.
The NotificationCenter is actually a combination of three design patterns: the Singleton, Mediator, and Observer patterns. It is based closely on the NSNotificationCenter included in Mac OS X's Cocoa framework.
A short example of the usage of a NotificationCenter:
require 'NotificationCenter' class Foo def foo NotificationCenter.instance.post('randomNotification', self) end end class Bar def initialize NotificationCenter.instance.add_observer(self, :notified, 'randomNotification', nil) end def notified(object) puts 'Got a randomNotification with object ' + object.inspect end end foo = Foo.new bar = Bar.new 5.times do |i| sleep(rand(5)) foo.foo end
Here, Foo defines a method foo that posts a notification to the default NotificationCenter. Bar registers to receive that notification, and defines a method to be called when it does receive it. We then create a new instance of each class, then call Foo#foo five times, sleeping a random amount of time between each call.
The output is something like the following:
Got a randomNotification with object #<Foo:0xc388c> Got a randomNotification with object #<Foo:0xc388c> Got a randomNotification with object #<Foo:0xc388c> Got a randomNotification with object #<Foo:0xc388c> Got a randomNotification with object #<Foo:0xc388c>
NotificationCenter.instance
NotificationCenter.new
NotificationCenter#add_observer(observer, selector, name, object)
nil
,
then the observer will be sent all notifications named name.NotificationCenter#delete_observer(observer)
nil
.NotificationCenter#post(name, object)
NotificationCenter#add_observer
to take a block instead of
selectorNotificationCenter#delete_observer
to remove registration
for a single notification instead of all at once