You are viewing a plain text version of this content. The canonical link for it is here.
Posted to java-user@lucene.apache.org by petite_abeille <pe...@mac.com> on 2002/06/28 03:36:37 UTC

[OT] how to write a simple notification center

Hello,

For those of you who are missing something akin to NSNotificationCenter 
in J2SE, here is an "experimental" (aka "not tested very much") Java 
implementation that somewhat mimics Apple's one.

If you are not sure what a notification center is about, you can check 
Apple's documentation:

http://developer.apple.com/techpubs/webobjects/Reference/Javadoc/com/webobjects/
foundation/NSNotificationCenter.html


There are four elements in this Notification class:


[Notification]

Same thing as NSNotification. Here is how to create a notification:

	new Notification( "ServiceAgent.WillProcessNotification", 
anAccount, null )

The parameters are the same as in NSNotification: notification name, 
object, and user info (a Map in that case).


[Notification.Observer]

This is the interface used by the observers to receive a notification.

	public void notify(Notification aNotification);


[Notification.Center]

This class mimic NSNotificationCenter. Here is how to register an 
observer:

	Notification.Center.defaultCenter().addObserver( this, 
"ServiceAgent.ExceptionNotification", null );

The parameters are the same as in NSNotificationCenter: observer, 
notification name, and object. There is no NSSelector necessary as the 
observer uses an interface (Notification.Observer) instead.

To create an "omniscient" observer, simply pass null for the 
notification name and object.

An observer with a null notification name but an object will "listen" to 
all notification "posted" by that object.

An observer with a null object but a notification name will "listen" to 
all notification with that name irrespectively of the "poster".


Here is how to post a notification:

	Notification.Center.defaultCenter().postNotification( new 
Notification( "ServiceAgent.WillProcessNotification", anAccount, 
null ) );


Of course you can create as many Notification.Center as you want in 
addition to the default center:

	new Notification.Center();


[Notification.Entry]

This is a private class that records an observer/notification 
name/object tuple. This class also decides if an observer is 
"interested" by a specific notification. Note the use of 
java.lang.ref.Reference for referencing the observer and the object.


[Notification.Task]

This private java.lang.Runnable class will "dispatch" the 
Notification.Observer.notify() method to a list of observers. This 
action, triggered by postNotification, take place in a separate thread.

Source code attached.

Comments welcome.

PA.