• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Observer Example

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I am posting an example of Observer Pattern. Please feel free to comment. This might also help people who are looking for Java Examples for Patterns.

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically



The Output
Notifying Observer Jack....
Price - 150.0
Notifying Observer Smith....
Price - 150.0

Regards,
Nikhil
 
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is standard implementation of this pattern in JDK:

java.util.Observable
java.util.Observer
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Another example ... for my own use I made an abstract publisher class. It provides methods to add and remove subscribers based on string keys but no publish method. I make an interface for each message type that is to be published. The concrete publisher implements the interface, as do the subscribers. So a concrete publisher has something like this for each method defined in the interface:

This is more hand coding than you'll find using Observable and Observer - usually almost exactly the 6 lines you see above - but has some neat advantages. I can publish any method name with any arguments. One publisher can have many methods. I can put logic in the publisher to do things like accumulate responses from subscribers for voting or polling, stop after any subscriber returns a success or failure flag, return values from the publish method, etc.

Another interesting variation has a queue per subscriber and puts message objects into the queue instead of calling the subscriber directly. That lets the publisher and subscriber work asynchronously and works even if the subscriber doesn't exist at the moment.

There is lots of fun to be had in pub-sub for sure.
 
reply
    Bookmark Topic Watch Topic
  • New Topic