05 Dec 2023



Advanced

The Observer Pattern defines a one-to-many dependency between objects so that when one object (subject) changes state, all of its dependents (observers) are notified and updated automatically. It is also known as the Publish-Subscribe pattern.

key points of the Observer Design Pattern:

  1. Intent:

    • The main intent of the Observer pattern is to define a one-to-many dependency between objects so that when one object (the subject) changes state, all its dependents (observers) are notified and updated automatically.
  2. Key Components:

    • Subject:
      • Maintains a list of observers and provides methods for attaching, detaching, and notifying observers of state changes. It is the object being observed.
    • Observer:
      • Defines an interface for receiving notifications from the subject. Observers register with the subject to receive updates.
    • ConcreteSubject:
      • Implements the Subject interface and is responsible for maintaining the state that observers are interested in. It notifies observers when the state changes.
    • ConcreteObserver:
      • Implements the Observer interface and receives notifications from the subject. It maintains a reference to the subject if it needs to query or update its state.
  3. Registration and Notification:

    • Observers register with the subject to receive notifications about changes in the subject's state. The subject maintains a list of registered observers and notifies them when its state changes.
  4. Push vs. Pull Model:

    • Push Model: The subject pushes information to the observers, sending them details about the state change.
    • Pull Model: The subject informs observers that a change has occurred, and observers pull the necessary information from the subject.
  5. Loose Coupling:

    • The Observer pattern promotes loose coupling between the subject and its observers. Observers are not tightly bound to the subject's implementation and can be added or removed without affecting the subject.
  6. Advantages:

    • Decoupling: It decouples the subject and observers, allowing them to vary independently.
    • Flexibility: It provides a flexible way to design relationships between objects, making it easy to add or remove observers.
    • Reusability: Observers can be reused across different subjects.
  7. Use Cases:

    • The Observer pattern is useful when a change in one object requires changing others, and the number of objects that need to be notified of the change is unknown or dynamic.
    • It is applicable when an object needs to notify others without making assumptions about who these objects are.

Example:

  • Consider a stock market application where multiple displays show the current stock prices. The stock market acts as the subject, and the displays act as observers. When the stock prices change, all displays are automatically updated.
software-design-patterns
observer-design-pattern