Want to Master Java Design Patterns?
Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!
Subscribe on YouTubeReal-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 usingsetChanged()andnotifyObservers(). -
JohnObserver & PeterObserver (Concrete Observers): Implement the
Observerinterface and override theupdate(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
-
Define Observers: Create classes like
JohnObserverandPeterObserverimplementingjava.util.Observerto receive and print notifications whenupdate()is invoked. -
Create the Observable: Subclass
java.util.Observableto createNokiaMobilePriceObservable. WhensetPrice()is called, flag the change withsetChanged()and notify listeners vianotifyObservers(). -
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
Observerinterface. - 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.
No comments:
Post a Comment