Observer Pattern in Java

“Life was always a matter of waiting for the right moment to act.” ~Anonymous.

Subject — Observer relation

Quora Excerpt:

  • Split-wise group : Anyone adds or updates any entry in the group — all members of group get a notification .

Code Findings:

  1. JavaScript event emitters.
document.getElementById('id').addEventListener('click', myListener);function myListener(e) {
e.preventDefault();
// do stuff as side effect
...
}

In the context of browsers, DOM objects serve as the subject of user interaction.

In our example code above, Document.getElementById('id')returns a reference to a DOM object with id="id", to which we subscribe a handler method using the addEventListener() method. Now, any time the DOM object is clicked by a user, the object emits an Event object.

There are multiple classes of Event objects which are extended varieties of the basic Event interface. This means most Event objects contain a number of universal properties and methods (e.g. type, target and preventDefault()) along with properties that are unique to the subtype class (e.g. clicks produce a MouseEvent, which contains position information such as clientX and clientY and keyboard information such as altKey or ctrlKey).

This pattern of Event objects being passed to event listeners is a great example of the observer pattern in implementation. It is important to note that the actual implementation of subjects/event emission is not done by the code we implement, but rather internally by the browser itself. This means that the DOM API exposes subjects to which listeners can be attached without directly revealing the steps where input/output gets translated to the emitted event.

2. Socket.io is also an example of observer pattern

Message Server Example

The below is a similar example for Message Server. When ever a client gets connected, they are added to the pool of observers. When somebody posts a message, all the people in the pools are called by there update method.

Project Structure

Implementation in Java

  1. Create the Subject i.e, the Topic which will send notification.

ISubject.java

MessageServer.java

2. Create Observer ie the one which gets notified after Topic change.

IObserver.java

Client.java

3. Create the Driver class.

Reference:

  • Ref 1 : About JavaScript event emitters.

Found it Interesting?
Please show your support by 👏. To read the complete series, click below.

Disclaimer:
I myself, has just started learning, design patterns. If you find any issues please feel free to post them in the comments section below. Thank you for reading so far 😄

Writes on Big Data, AWS & Backend technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store