DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Security by Design: Building Full-Stack Applications With DevSecOps
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Building Security into the Feature During the Design Phase
  • Build a Scalable E-commerce Platform: System Design Overview

Trending

  • Memory-Optimized Tables: Implementation Strategies for SQL Server
  • Strategies for Securing E-Commerce Applications
  • Designing AI Multi-Agent Systems in Java
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt

Observer Design Pattern in a Nutshell

Want to learn more about the Observer design pattern? Check out this post to learn more about using Subjects and Observers in this behavioral design pattern.

By 
Yogen Rai user avatar
Yogen Rai
·
Updated Oct. 30, 18 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
21.4K Views

Join the DZone community and get the full member experience.

Join For Free

The Observer pattern, also known as the Publish-Subscriber pattern, is one of the behavioral design patterns that defines a one-to-many relationship between objects. For example, when the state of one object, Subject, changes, all its dependents, Observers, are notified and updated automatically by calling their methods.

Mainly, this pattern is used to implement distributed event handling systems. It is also a key part in the Model-View-Controller (MVC) architectural pattern.

Structure

The structure of the Observer pattern is shown below:

observer-pattern-class


Figure: Observer Pattern Structure

Here, Subject has a list of Observers, e.g. ConcreteObserverA and ConcreteObserverB. Whenever there is a change in state of an object in Subject, all of the objects of the concrete implementation of the Observerclass will be updated via their update function.

Example

Here, we've presented a more practical example that will hopefully help you to understand this pattern a bit more.

The class diagram of the system is:

stockmarket-class-diagram

Figure: Observer Pattern Example - Stock Update Notification

Here, StockMarket is the subject and StockBroker is the Observer. StockBroker has two concrete implementations:StockBuyer andStockViewer. So, whenever the stockMarket object is changed, these two concrete observers get an update via their function update().

Let's look at the sequence diagram to make understanding more clear.

obeserver-pattern-sequence

Figure: Sequence Diagram for Stock Market Add

Whenever a stock value is updated for a symbol, then subscribers StockBuyer  and StockViewer of the StockMarket will get updated information.

Java Implementation

Below is the Java implementation of the system described above.

Let's start by creating the interface StockBroker  as an interface for the observer.

import java.util.Map;
/**
 * Observer interface
 */
interface StockBroker {
    void update(Map<String, Double> stockList);
}


These are the concrete implementations of the abstract observer.

import java.util.Iterator;
import java.util.Map;

/**
 * Here, StockBuyer and StockViewer are concrete Observers
 */
public class StockBuyer implements StockBroker {

    public void update(Map<String, Double> stocks) {
        System.out.println("StockBuyer: stockList is changed:");
        stocks.forEach((symbol, value) -> System.out.println(symbol + " - $" + value));
    }
}
public class StockViewer implements StockBroker {

    public void update(Map<String, Double> stocks) {
        System.out.println("StockViewer: stockList is changed:");
        stocks.forEach((symbol, value) -> System.out.println(symbol + " - $" + value));
    }
}


Now, we've created a Subject class that notifies all the Observers upon the change in state.

/**
 * Subject
 */
public abstract class AbstractStockMarket {
    private List<StockBroker> stockBrokers = new ArrayList<StockBroker>();

    public void addStockBroker(StockBroker stockBroker) {
        stockBrokers.add(stockBroker);
    }

    public void notifyStockBroker(Map<String, Double> stockList) {
        for (StockBroker broker : stockBrokers) {
            broker.update(stockList);
        }
    }

    public abstract void addStock(String stockSymbol, Double price);

    public abstract void update(String stockSymbol, Double price);
}


We could have combined the two above Subject classes. However, the separation of them provides an extra layer and the extensibility on future classes.

The following code represents the concrete Subject.

/**
 * It is concrete Subject
 */
public class StockMarket extends AbstractStockMarket {

    private Map<String, Double> stockList = new HashMap<>();

    public void addStock(String stockSymbol, Double price) {
        stockList.put(stockSymbol, price);
    }

    public void update(String stockSymbol, Double price) {
        stockList.put(stockSymbol, price);
        notifyStockBroker(stockList);
    }
}


So finally, here is the application class used to implement the above classes.

/**
 * Client
 */
public class Application {
    public static void main(String[] args) {
        AbstractStockMarket market = new StockMarket();

        StockBroker buyer = new StockBuyer();
        StockBroker viewer = new StockViewer();

        market.addStockBroker(buyer);
        market.addStockBroker(viewer);

        market.addStock("ORC", 12.23);
        market.addStock("MSC", 45.78);
        System.out.println("===== Updating ORC =====");
        market.update("ORC", 12.34);
        System.out.println("===== Updating MSC =====");
        market.update("MSC", 44.68);
    }
}


The output of the program is:

===== Updating ORC =====
StockBuyer: stockList is changed:
ORC - $12.34
MSC - $45.78
StockViewer: stockList is changed:
ORC - $12.34
MSC - $45.78
===== Updating MSC =====
StockBuyer: stockList is changed:
ORC - $12.34
MSC - $44.68
StockViewer: stockList is changed:
ORC - $12.34
MSC - $44.68

You can see every subscriber gets an update notification when there is a change in the price of the stock.

Potential Issue

The Observer design pattern can cause memory leaks in the basic implementation and requires both explicit attachment and explicit detachment. This is because the subject holds strong references to the observers, keeping them alive. This is also referred to as the lapsed-listener problem. 

This issue can be eliminated by the Subject holding weak references to the Observers. 

Conclusion

This post talked about the summarized form of the Observer Design Pattern, as one of the GOF patterns, with a simple example. 

The source code for all example presented above is available on GitHub with an additional example of a banking application.

Happy coding!

Design

Published at DZone with permission of Yogen Rai, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Security by Design: Building Full-Stack Applications With DevSecOps
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Building Security into the Feature During the Design Phase
  • Build a Scalable E-commerce Platform: System Design Overview

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!