Easy patterns: Observer

Ruslan Malogulko
ITNEXT
Published in
2 min readJun 23, 2018

--

This article is created in continuation to series of easy patterns description and describes behavioral pattern for notification objects about changes in another object, they’re interested in.

Currently you can find articles for such patterns:

Creational patterns:

Simple Factory

Factory method

Builder

Singleton

Abstract factory

Prototype

Structural patterns:

Adapter

Decorator

Bridge

Composite

Facade

Flyweight

Proxy

Behavioral patterns:

Visitor

Mediator

Observer (this article)

Memento

Iterator

Chain Of Responsibility

Strategy

State

The main essence

Observer pattern determines relation between two objects: Observer and Subscriber. So, when one object (observer) is changed, other one or many (subscriber) would know that immediately.

Real life example. Publisher agency publishing magazine for airports. Airports are interested in getting fresh magazine each month, so they’re subscribing for its updates. Once new version is published, they’re getting notification about that. Once airport realize that there is no need in magazine subscription any more, it’s possible to unsubscribe of getting notifications.

Example of use

In example we’re creating new publisher and couple of airports (1,2). After that subscribing them for getting notifications by concrete magazine type (3). Finally, once new magazine is published, notifying airports about that (4).

Profit

This pattern helps to manage relations between two objects, one of which is updated. Observer pattern guaranties that once one object is updated, all other objects are notified about that fact immediately.

Weak places

The observer pattern can cause memory leaks known as lapsed listener problem because the subject holds strong references to the observers, keeping them alive.

The observer pattern stimulates you to have global state. This means that side effects can cause unpredictable and non obvious changes into global state of application.

The observer pattern cause tightly coupling between objects, so they know and have access to each other.

Conclusion

If you found this article helpful, please hit the 👏 button and feel free to comment below!

--

--