Observer Pattern Explained: Code Demo and Real‑World Use Cases
This article introduces the Observer pattern, explains its purpose of decoupling publishers and subscribers, walks through a complete Java implementation with an official‑account subscription example, lists typical business scenarios, compares it with the Mediator pattern, and outlines its advantages and pitfalls.
Observer Pattern Overview
Defines a subject (publisher) and multiple observers (subscribers). Observers register with the subject; when the subject’s state changes, it pushes a message to all registered observers without polling.
Goal: achieve publish‑subscribe decoupling, one‑to‑many coordination, and allow adding new listeners without modifying the publisher.
Typical Scenarios
Public account subscription: a blogger posts a new article and all followers receive a push notification.
Software contexts: message event bus, Spring event listeners, front‑end Vue reactive data.
Order status changes trigger SMS, app push, inventory sync, and log collection.
Java Implementation – Official Account Subscription Example
1. Observer interface
public interface Observer {
// Receive messages pushed by the subject
void update(String msg);
}2. Subject abstract class
import java.util.ArrayList;
import java.util.List;
public abstract class Subject {
// Store all subscribed observers
private List<Observer> observerList = new ArrayList<>();
// Subscribe
public void attach(Observer observer){
observerList.add(observer);
}
// Unsubscribe
public void detach(Observer observer){
observerList.remove(observer);
}
// Notify all observers
public void notifyAllObservers(String msg){
for (Observer obs : observerList){
obs.update(msg);
}
}
}3. Concrete subject: OfficialAccount
public class OfficialAccount extends Subject{
// Publish a new article
public void publishArticle(String content){
System.out.println("公众号发布新文章:" + content);
// Push to all fans
notifyAllObservers(content);
}
}4. Concrete observer: Fan
public class Fan implements Observer{
private String name;
public Fan(String name){
this.name = name;
}
@Override
public void update(String msg) {
System.out.println(name + " 收到推送:新文章《" + msg + "》");
}
}5. Test driver
public class Test {
public static void main(String[] args) {
OfficialAccount account = new OfficialAccount();
Observer fan1 = new Fan("小明");
Observer fan2 = new Fan("小红");
account.attach(fan1);
account.attach(fan2);
// Publish an article, automatically push to everyone
account.publishArticle("23种设计模式完整教程");
}
}Common Business Use Cases
Publish‑subscribe systems: event bus, message queues, system event notifications.
Data synchronization: order status changes propagate to inventory, points, SMS alerts.
UI reactive frameworks: front‑end listeners, automatic page refresh.
Spring ApplicationEvent underlying mechanism.
Log, telemetry, and multi‑channel monitoring collection.
Advantages and Drawbacks
Advantages: complete decoupling of publisher and subscriber, easy addition of new listeners without changing publisher code, supports dynamic subscription and unsubscription.
Drawbacks: notification latency grows with many observers; circular dependencies can cause infinite loops, requiring proper disposal of listeners.
Mediator vs Observer
Mediator: multiple objects interact pairwise through a central mediator.
Observer: a single subject pushes messages unidirectionally to multiple subscribers.
Design Patterns Summary (Behavioral Category)
Chain of Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Visitor
State
Strategy
Template Method
Observer
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
liandk
Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
