Observer Design Pattern

Get an overview of the observer design pattern.

Overview

Suppose that we want to buy some electronic items from a store. The store near us often puts items on sale or gives special offers. But when we visit the store, we find out that there’s no sale going on. We could visit the store every day and check for discounts and offers, but we can quickly see the problem: we’re making lots of pointless visits to the store. How can we solve this problem?

One solution would be to give our contact information to the store, and the storekeeper could contact us once the sale starts. This would be beneficial because we wouldn’t need to make pointless visits to the store. This is the crux of the observer design pattern.

Definition

The observer design pattern defines 1-to-n dependencies between objects so that changes to one object cause all dependent objects to be notified.

Explanation

To understand this definition, let’s map it to our example. The person (buyer) buying electric equipment depends on the shop. We can safely assume that there will be multiple buyers in the same store. The observer pattern defines a relationship from one shop to many buyers so that buyers will be notified about sales.

Type

The observer is a software design pattern that falls into the behavioral design.

Structure

Get hands-on with 1200+ tech skills courses.