乐闻世界logo
搜索文章和话题

What is the Difference Between Publish-Subscribe Pattern and Observer Pattern?

2024年6月24日 16:43

Observer Pattern

Definition and Working Principle:

In the Observer Pattern, the 'Subject' object manages a collection of dependent objects, referred to as 'Observers'. Upon a change in the subject's state, it automatically notifies all registered observers. This pattern is commonly used in distributed event handling systems where modifications to one object's state influence one or more other objects.

Characteristics:

  • Direct communication: The subject communicates directly with its observers without intermediaries.
  • Tight coupling: Observers must register with the subject to receive updates.
  • Synchronous updates: Observers receive state update notifications synchronously.

Example:

Imagine a stock market application where a 'Stock' object (Subject) monitors changes in stock prices. Investor objects (Observers) register with the Stock object to receive price updates. When the stock price changes, the Stock object notifies all registered investors.

Publish-Subscribe Pattern

Definition and Working Principle:

In the Publish-Subscribe Pattern, message passing between components is mediated by middleware such as a 'Message Broker' or 'Event Bus', which maintains a topic-subscriber mapping. Publishers send messages to the message broker, not directly to subscribers. The message broker then distributes messages to all subscribers registered for the relevant topic.

Characteristics:

  • Decoupled communication: Publishers and subscribers are unaware of each other's existence and communicate through the message broker.
  • Scalability: The system allows easy addition of more publishers or subscribers without impacting other components.
  • Asynchronous processing: Subscribers handle received messages asynchronously.

Example:

In the same stock market application, various services or components can publish messages regarding stock price updates to the message broker. Investors do not interact directly with the stock object or services; instead, they subscribe to stock price update messages. The message broker distributes updates to all subscribers, who may process these messages asynchronously.

Summary of Differences

  • Communication method: In the Observer Pattern, observers communicate directly with the subject; in the Publish-Subscribe Pattern, publishers and subscribers communicate through a message broker.
  • Coupling level: The Observer Pattern exhibits higher coupling between the subject and observers, while the Publish-Subscribe Pattern promotes lower coupling.
  • Synchronous vs. asynchronous: The Observer Pattern is synchronous, with observers receiving notifications immediately; the Publish-Subscribe Pattern supports asynchronous processing, enabling subscribers to handle messages at a later time.
标签:设计模式