Files
design-patterns/03-behavioral/observer/README.md

1.7 KiB

Observer Design Pattern — Java Example

Pattern: Behavioral → Observer Article: https://ankurm.com/observer-design-pattern-java/

What this example shows

A stock market subject that notifies subscribers without knowing what they do with the notification. StockObserver is the one-method interface every subscriber implements. StockMarket is the subject: it holds the observer list and pushes both the old and new price to every subscriber whenever setPrice() is called. AlertObserver and PortfolioObserver are two concrete observers that react completely differently to the same notification — one watches for threshold breaches, the other computes a P&L delta. Main subscribes all three, moves the price twice, then unsubscribes Bob before a third move so his portfolio observer never sees it.

How to run

javac observer/*.java -d out/observer
java -cp out/observer observer.Main

Requires Java 25.

Post Section ↔ File Mapping

Post Section File(s)
Implementation: Stock Price Monitoring — the Observer interface StockObserver.java
Implementation: Stock Price Monitoring — the Subject StockMarket.java
Implementation: Stock Price Monitoring — AlertObserver AlertObserver.java
Implementation: Stock Price Monitoring — PortfolioObserver PortfolioObserver.java
Implementation: Stock Price Monitoring — wiring it together Main.java

Note: the "Push vs Pull Notification Models" pull-model snippet (PullAlertObserver) and the "Thread Safety" CopyOnWriteArrayList snippet are illustrative only — they are not part of this repository's runnable example.

Article: https://ankurm.com/observer-design-pattern-java/ All patterns: https://ankurm.com/design-patterns-java/