Sunday, 17 March 2019

Example of Observer and Observable in Java? | Observer and Observable

Want to Master Java Design Patterns?

Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!

Subscribe on YouTube

Real-Time Example: Mobile Price Tracking Alert System

The Observer Design Pattern is widely applied in real-time notification systems, such as e-commerce price alerts, stock market updates, and live score trackers. In Java, this pattern can be implemented directly using the built-in java.util.Observer interface and java.util.Observable class.

In this scenario, a mobile phone's price changes dynamically, and multiple registered customers (observers) need to be instantly informed whenever an update occurs.

Core Participants in the Application

  • NokiaMobilePriceObservable (Subject/Observable): Extends Observable. It maintains the product price attribute and dispatches updates using setChanged() and notifyObservers().
  • JohnObserver & PeterObserver (Concrete Observers): Implement the Observer interface and override the update(Observable o, Object arg) method to react to price revisions.
  • ObservableDemo (Driver Class): Registers the observers with the observable and simulates changing the product price to trigger notifications.

Step-by-Step Implementation Flow

  1. Define Observers: Create classes like JohnObserver and PeterObserver implementing java.util.Observer to receive and print notifications when update() is invoked.
  2. Create the Observable: Subclass java.util.Observable to create NokiaMobilePriceObservable. When setPrice() is called, flag the change with setChanged() and notify listeners via notifyObservers().
  3. Subscribe & Trigger: In the client code, instantiate the mobile observable with an initial price, attach both observers using addObserver(), and update the price to observe automatic event delivery.

Why Use Observer and Observable?

  • Loose Coupling: The observable subject does not need to know the internal implementation details of John or Peter; it only interacts via the standard Observer interface.
  • Broadcasting Capabilities: Supports one-to-many communication, allowing any number of interested observers to subscribe or unsubscribe at runtime.
  • Clean Event Architecture: Eliminates continuous polling by letting the subject automatically push data updates as soon as state changes happen.

Related Observer Pattern Tutorials to Watch Next

No comments:

Post a Comment

Tutorials