Behavioral Patterns - Observer Pattern Exercise


The Observer Pattern is widely used to solve one-to-many object state changes notification problems. The pub/sub model uses the Observer Pattern as the base pattern. It is also used in the event-driven systems. In this exercise, we will create a naive implementation of the pub/sub model to understand the components of the Observer Pattern.

Reading Materials

  1. (10 minutes reading)

Practice Materials

  1. Use the Observer Pattern to create a naive implementation of the pub/sub model.


  1. Observer (The interface that defines the callback method signature or the update method when it is notified.) - Observer
  2. Subject (The interface that observers listen to) - Subject
  3. AbstractSubscriber (The abstract class that attach the observer to a subject) - AbstractSubscriber
  4. AbstractTopic (The abstract class that keep track of a list of observers and provides observer registration implementations) - AbstractTopic
  5. TextMessageSubscriber (The concrete class that represents a subscriber that will print out the message that is published) - TextMessageSubscriber
  6. TextMessageTopic (The concrete class that represents a topic that defines the message publishing implementation) - TextMessageTopic
  7. Client (The class that creates topics and subscribers, registers and unregisters them, and publishes messages to topics) - App


  • A Queue could be used to keep track of published message to the Topic. After notifying all subscribers about the head message of the queue, the message should be dequeued.


Pub/Sub Example

Questions to discuss

  1. What are the common use cases to apply an Observer Pattern?


Popular posts from this blog

Creating a Library Project for Spring Boot

Spring Data Repository Query Precedence Tricks

Overwriting Spring Security Context through Filter