I have a publisher class that is producing events, and a bunch of listener cla开发者_运维技巧sses that want to subscribe to the events in order to run their own callbacks.
All of these listener classes are known in advance.
What's the best way for all my listeners to subscribe to the publisher at application init time? I would prefer all the code specific to a listener be part of the listener class. I was thinking the listener could subscribe to the publisher in a static block (Object), but from what I understand Java lazy loads classes so there's no guarantee all the listeners will be subscribed immediately. To circumvent that, I could potentially do something to force the JVM to load all my listeners immediately?
Is there something simpler that I'm missing?
Use actors! One actor for each publisher and one actor for each subscriber. The publisher maintains a list of subscribers. Subscribers are added by messaging the publisher with something like: pub ! add(sub)
When the publisher has something to publish, it iterates through its list of subscribers and messages each one. See http://www.scala-lang.org/node/242 for actor intro.
It is better to use some controlled runtime environment like OSGi or RCP, foundation of the Eclipse. They offer a lot of ways for declarative control of application load process and establishing compile- and run-time dependencies between modules.
For example you can package all of your listeners as separate bundles, mark all of them as not lazy loaded and add subscribing code to the init hooks.
精彩评论