Observer Pattern in Java

Observer Pattern is a Behavioral Pattern in which, an Object (we call it Subject) contains a list of dependency Objects (we call them Observers). Observers will be notified and updated automatically whenever Subject changes its state. Today we’re gonna look at how Observer Pattern in Java works.


Observer Pattern defines one-to-many relationship between Subject and Observers:
– The Subject maintains a list of Observers and has methods for adding, removing and notifying its Observers.
– When Subject changes its state, all Observers are notified and updated automatically.
– The Subject only know list of Observers and doesn’t care how they implement.
The image below shows how they interact with each other.

1. Project Overview

To build an example for Observer Pattern, we will create some interfaces and their implementations.

Our goal is making a FanPage, and Fans who followed it will be notified automatically whenever FanPage create its schedule. After that, Fans wil update their own schedules depending on FanPage schedule. Fan also has the ability to unsubscribe FanPage.

It’s a little bit difficult. So we should look at an upgraded diagram of our Observer Pattern:

2. Step by Step

2.1- Create Observer interface:

2.2- Create Subject interface:

2.3- Create implementation of Subject interface – FanPage class:

2.4- Create implementation of Observer interface – Fan class:

2.5- Create Test Class:

2.6- Run the code, the console window shows:



By grokonez | February 26, 2017.

Last updated on June 4, 2017.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *