Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Producer/Consumer pattern and Observer Pattern

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 )

like image 984
Kunal Sharma Avatar asked Nov 06 '16 04:11

Kunal Sharma


People also ask

What is observation pattern?

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.

What is an Observer pattern give an example?

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.

What is Producer consumer pattern?

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.

Is Kafka an Observer pattern?

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.


1 Answers

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.

like image 124
taskinoor Avatar answered Oct 08 '22 17:10

taskinoor