Observer (aka Publish-Subscribe | Dependents)

Intent

  • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Problems

  • A one-to-many dependency between objects should be defined without making the objects tightly coupled.

  • When one object changes state, an open-ended number of dependent objects should be updated automatically.

  • An object can notify multiple other objects.

Solutions

  • Define Subject and Observer objects so that when a subject changes state, all registered observers are notified and updated automatically.

Advantages

✅ Open/Closed Principle. You can introduce new subscriber classes without having to change the publisher’s code (and vice versa if there’s a publisher interface). ✅ You can establish relations between objects at runtime.

Disadvantages

❌ Subscribers are notified in random order.

Last updated