Skip to main content

Observer

Sumanth TatipamulaAbout 3 minBehavioralDesign PatternsJavaObserver

Introduction

  • Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.

GOF Definition

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

  • This is model is also called Publisher - Subscriber Model.

  • One can remove or add Subscribers in realtime.

  • The subscribers need not be of same type.

    • A company has both employees and customers who can purchase the company stocks. As a result, they like to get alerts when the stock price changes. In this case, both customers and employees are the observers and the company is the subject.

Terms

  • In this pattern there are two types of objects. One is observer and the other is the subject.

  • Observer: It is an object that needs to be informed when interesting stuff happens in another object.

  • Subject: The object about whom an observer is interested is called object.

Pictorial Explanation

  • Step - 1: Three Observers request notification from a subject.
  • Step - 2: Subject can grant the requests; the connection is established.
  • Step - 3: Subject sends notifications to the registered users
  • Step - 4: Observer2 does not wants to get further notifications and requests to unregister themselves. So only Observer1 and Observer3 receives notifications

Real World Examples

  • Users subscribing to youtube channel.

  • People following celebrities in Social Media

Example

  • Implementation of event listeners in graphical user interfaces (GUIs). Let's consider a simple scenario where you have a button in a GUI, and you want to perform some action when the button is clicked. Here's how you can use the Observer pattern to achieve this:

  • In this example, the Button class acts as the subject that maintains a list of observers (listeners) implementing the ActionListener interface. The Button class provides methods to add and remove listeners and a click() method to simulate a button click event.

  • The LoggingListener and EmailNotificationListener are concrete observer classes that implement the ActionListener interface. They define their respective actions to be performed when the button is clicked.

  • In the main() method, observers (listeners) are created and registered with the button using the addActionListener() method. When the button's click() method is called, it notifies all the registered listeners by calling their actionPerformed() method. In this case, both the logging and email notification actions will be performed.

UML Diagram

Difference between Command and Observer

Command PatternObserver Pattern
PurposeEncapsulates a request or operation as an object. Supports parameterization, queuing or logging of requests, and undoable operations.Establishes a one-to-many dependency between objects. Notifies and updates observers when changes occur in the subject.
StructureConsists of invoker, command, and receiver. Invoker holds and executes command objects. Command encapsulates receiver's action. Receiver performs the actual operation.Comprises subject and observer. Subject maintains a list of observers and notifies them when its state changes.
InteractionInvoker decides when and how to execute commands. Command objects encapsulate specific actions or requests. Requester remains decoupled from the receiver.Observers register themselves with the subject. Subject broadcasts notifications to all observers when changes occur.
Use CasesUseful for decoupling and encapsulating requests, parameterizing clients with different requests, storing requests in a queue, logging commands, or implementing undo/redo functionality.Suitable for establishing dependencies between objects, automatic updates and notifications. Commonly used in event handling, GUI frameworks, and reactive programming.