Design Patterns – Polling for Events vs. Observer Pattern

design-patterns

Are there scenarios where polling for events would be better than using the observer pattern? I have a fear of using polling and would only start using it if someone gave me a good scenario. All I can think of is how the observer pattern is better than polling. Conside this scenario:

You are programming a car simulator. The car is an object. As soon as the car turns on, you
want to play a "vroom vroom" sound clip.

You can model this in two ways:

Polling: Poll the car object every second to see if it's on. When it's on, play the sound clip.

Observer pattern: Make the car the Subject of the observer pattern. Have it publish the "on" event to all observers when itself turns on. Create a new sound object that listens to the car. Have it implement the "on" callback, which plays the sound clip.

In this case, I think the observer pattern wins. Firstly, polling is more processor intensive. Secondly, the sound clip does not immediately fire when the car turns on. There can be up to a 1 second gap because of the polling period.

Best Answer

Imagine you want to get notified about every engine cycle, e.g. to display an RPM measurement to the driver.

Observer pattern: The engine publishes an "engine cycle" event to all observers for each cycle. Create a listener that counts events and updates the RPM display.

Polling: The RPM display asks the engine at regular intervals for an engine cycle counter, and updates the RPM display accordingly.

In this case, the observer pattern would probably loose: the engine cycle is a high-frequency, high-priority process, you don't want to delay or stall that process just to update a display. You also don't want to thrash the thread pool with engine cycle events.


PS: I also use the polling pattern frequently in distributed programming:

Observer pattern: Process A sends a message to process B that says "each time an event E occurs, send a message to Process A".

Polling pattern: Process A regularly sends a message to process B that says "if you event E occured since the last time I've polled, send me a message now".

The polling pattern produces a bit more network load. But the observer pattern has downsides, too:

  • If process A crashes, it will never unsubscribe, and process B will try to send notifications to it for all eternity, unless it can reliably detect remote process failures (not an easy thing to do)
  • If event E is very frequent and/or the notifications carry a lot of data, then process A might get more event notifications than it can handle. With the polling pattern, it can just throttle the polling.
  • In the observer pattern, high load can cause "ripples" through the whole system. If you use blocking sockets, these ripples can go both ways.
Related Topic