DEV Community

jzfrank
jzfrank

Posted on

HFDP(2) - Observer Pattern

In this post we introduce the observer pattern.

You may have subscribed some newspaper or podcasts. Whenever they have new releases, you get notified, and you go and see what's happening. This, could be further abstracted to Observer Pattern. You are the observer, and the newspaper is the subject/observable.

Observer Pattern involves a subject/observable (e.g. newspaper) and an observer (e.g. you, the loyal reader). The subject should be able to add or remove observers, and whenever something changes in the subject, the observer should be notified and do something accordingly (e.g. update display). The Observer should be able to subscribe the subject.

Formal Definition

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

one-to-many-relationship

the class diagram

Of course, the Subject may be a superclass instead of an interface.

Design Principle

  • Strive for loosely coupled designs between objects that interact.

The Subject and the Observer are loosely coupled, because both of them don't have to know the nitty-gritty details of each other. All they know is the other implements a certain interface.

Implementation

We can implement the observer pattern by ourselves or use java.util.Observer/Observable.

Example

Consider the front-end UI button. We usually add actionListener to it. So the button is the Subject/Observable and the actionListener is the Observer.

Top comments (0)