I would like to understand the difference between the Observer Pattern and the most common problem of Producer/Consumer , Since both require synchronization so that the changes are available , and How do i go implement both ( if they are different )
The observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
Observer is a behavioral design pattern. It specifies communication between objects: observable and observers. An observable is an object which notifies observers about the changes in its state. For example, a news agency can notify channels when it receives news.
The producer consumer pattern is a concurrency design pattern where one or more producer threads produce objects which are queued up, and then consumed by one or more consumer threads. The objects enqueued often represent some work that needs to be done.
The observer pattern is generally implemented in a single-application scope. On the other hand, the publisher-subscriber pattern is mostly used as a cross-application pattern (such as how Kafka is used as Heart of event-driven architecture) and is generally used to decouple data/event streams and systems.
The difference between them is the nature of synchronization required.
In case of observer pattern whenever a change of interest is made in observed object all observers are notified immediately. So immediate per change synchronization is required by the pattern. In fact observer patterns doesn't require a different thread. The thread which is changing observed object can notify all registered observers.
However, in case of producer-consumer the only required synchronization is consumer must wait when there is no element and producer must wait when the buffer is full. But per object synchronization is not required. Producer can produce multiple objects before consumer consume any of them and consumer can consume multiple objects in one go. So immediate notification like observer is not needed here.
As far as the implementation, you can have a look at Wikipedia articles for them: Observer Pattern and Producer-Consumer Problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With