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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Architecture and Code Design, Pt. 2: Polyglot Persistence Insights To Use Today and in the Upcoming Years
  • Double-Checked Locking Design Pattern in Java
  • Messaging Design Pattern (MDP) In Java

Trending

  • Streamlining Event Data in Event-Driven Ansible
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • Emerging Data Architectures: The Future of Data Management
  • Rust and WebAssembly: Unlocking High-Performance Web Apps
  1. DZone
  2. Coding
  3. Java
  4. Observer Design Pattern In Java

Observer Design Pattern In Java

By 
Brijesh Saxena user avatar
Brijesh Saxena
DZone Core CORE ·
Oct. 12, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
12.2K Views

Join the DZone community and get the full member experience.

Join For Free

Today, I will discuss simple and very useful behavioral design pattern called — Observer Design Pattern. This design pattern is useful when we want get notified about changes in the object state.

Observer Design Pattern

  • The Observer Design Pattern maintains one-to-many dependency between Subject (Observable) and its dependents (Observer) in such a way that whenever state of Subject changes, its dependents get notified.
  • The Observer Design Pattern is a design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. 
  • The Observer Design Pattern is used when we like to have notification upon changes in the objects state.
  • The Observer Design Pattern is one of twenty-three well known Gang of Four design patterns that defines an one-to-many dependency objects so that when one object changes state, all of its dependents get notified and updated automatically.
  • The Observer Design Pattern is mainly used to implement distributed event handling , in "event driven" system.
  • In such systems, the subject is usually called a "source of events", while the observers are called "sink of events".
  • Most modern languages have built-in "event" constructs which implement the observer pattern components.
  • Java also offers Observer and Observable to support built-in event constructs for implementing observer pattern. These are available since Java 1. 
  • But, in Java 9 these are declared deprecated/obsolete because the event model supported by Observer and Observable is quite limited, the order of notifications delivered by Observable is unspecified, and state changes are not in one-for-one correspondence with notifications. For a richer event model, consider using the java.beans package. For reliable and ordered messaging among threads, consider using one of the concurrent data structures in the java.util.concurrent package. For reactive streams style programming, see the Flow API.  (read more on Deprecate Observer and Observable).  

observer design pattern

Now an example to understand the implementation of Observer Design Pattern.

Suppose there are some public figures like politicians or celebrities for which there are some followers.  Whenever these public figures do any tweet, there registered followers get the notification on that. 

Tweet Notification Example using Observer Design Pattern

First we will define the Subject interface:

Java
xxxxxxxxxx
1
10
9
 
1
package org.trishinfotect.observer;
2

          
3
public interface Subject {
4
    public void addSubscriber(Observer observer);
5

          
6
    public void removeSubscriber(Observer observer);
7

          
8
    public void notifySubscribers(String tweet);
9
}


Then we will create Observer interface:

Java
xxxxxxxxxx
1
 
1
package org.trishinfotect.observer;
2

          
3
public interface Observer {
4
    public void notification(String handle, String tweet);
5
}


Then we will create concrete subject class called PublicFigure:

Java
xxxxxxxxxx
1
51
 
1
package org.trishinfotect.observer;
2

          
3
import java.util.ArrayList;
4
import java.util.List;
5

          
6
public class PublicFigure implements Subject {
7

          
8
    protected List<Observer> observers = new ArrayList<Observer>();
9
    protected String name;
10
    protected String handle;
11

          
12
    public PublicFigure(String name, String handle) {
13
        super();
14
        this.name = name;
15
        this.handle = "#" + handle;
16
    }
17

          
18
    public String getName() {
19
        return name;
20
    }
21

          
22
    public void setName(String name) {
23
        this.name = name;
24
    }
25

          
26
    public String getHandle() {
27
        return handle;
28
    }
29

          
30
    public void tweet(String tweet) {
31
        System.out.printf("\nName: %s, Tweet: %s\n", name, tweet);
32
        notifySubscribers(tweet);
33
    }
34

          
35
    @Override
36
    public synchronized void addSubscriber(Observer observer) {
37
        observers.add(observer);
38
    }
39

          
40
    @Override
41
    public synchronized void removeSubscriber(Observer observer) {
42
        observers.remove(observer);
43
    }
44

          
45
    @Override
46
    public void notifySubscribers(String tweet) {
47
        observers.forEach(observer -> observer.notification(handle, tweet));
48
    }
49

          
50
}


Please notice that we have APIs for adding and removing followers. We also have API for notifying followers. And we also have API to tweet. The tweet API does notify to its registered followers. While notifying followers, the subject also provides information regarding the change done. In our example its tweet which changes. So, it's in the parameter of notification. So, in short Subject should also give the context of change to its followers for notification. Without that it observer pattern will not be very effective. Every subject maintains it's list of followers. 

Now we will define Follower class:

Java
xxxxxxxxxx
1
18
 
1
package org.trishinfotect.observer;
2

          
3
public class Follower implements Observer {
4

          
5
    protected String name;
6

          
7
    public Follower(String name) {
8
        super();
9
        this.name = name;
10
    }
11

          
12
    @Override
13
    public void notification(String handle, String tweet) {
14
        System.out.printf("'%s' received notification from Handle: '%s', Tweet: '%s'\n", name, handle, tweet);
15
    }
16

          
17
}


Now, its time to write a Main program to execute and test the output:

Java
xxxxxxxxxx
1
33
 
1
package org.trishinfotect.observer;
2

          
3
public class Main {
4

          
5
    public static void main(String args[]) {
6
        PublicFigure bobama = new PublicFigure("Barack Obama", "bobama");
7
        PublicFigure nmodi = new PublicFigure("Narendra Modi", "nmodi");
8

          
9
        Follower ajay = new Follower("Ajay");
10
        Follower vijay = new Follower("Vijay");
11
        Follower racheal = new Follower("Racheal");
12
        Follower micheal = new Follower("Micheal");
13
        Follower kim = new Follower("Kim");
14

          
15
        bobama.addSubscriber(ajay);
16
        bobama.addSubscriber(vijay);
17
        bobama.addSubscriber(racheal);
18
        bobama.addSubscriber(micheal);
19
        bobama.addSubscriber(kim);
20

          
21
        nmodi.addSubscriber(ajay);
22
        nmodi.addSubscriber(vijay);
23
        nmodi.addSubscriber(racheal);
24
        nmodi.addSubscriber(micheal);
25
        nmodi.addSubscriber(kim);
26

          
27
        bobama.tweet("Hello Friends!");
28
        nmodi.tweet("Vande Matram!");
29
        bobama.removeSubscriber(racheal);
30
        bobama.tweet("Stay Home! Stay Safe!");
31
    }
32
}


And here's the output:

Java
x
21
 
1
Name: Barack Obama, Tweet: Hello Friends!
2
'Ajay' received notification from Handle: '#bobama', Tweet: 'Hello Friends!'
3
'Vijay' received notification from Handle: '#bobama', Tweet: 'Hello Friends!'
4
'Racheal' received notification from Handle: '#bobama', Tweet: 'Hello Friends!'
5
'Micheal' received notification from Handle: '#bobama', Tweet: 'Hello Friends!'
6
'Kim' received notification from Handle: '#bobama', Tweet: 'Hello Friends!'
7

          
8
Name: Narendra Modi, Tweet: Vande Matram!
9
'Ajay' received notification from Handle: '#nmodi', Tweet: 'Vande Matram!'
10
'Vijay' received notification from Handle: '#nmodi', Tweet: 'Vande Matram!'
11
'Racheal' received notification from Handle: '#nmodi', Tweet: 'Vande Matram!'
12
'Micheal' received notification from Handle: '#nmodi', Tweet: 'Vande Matram!'
13
'Kim' received notification from Handle: '#nmodi', Tweet: 'Vande Matram!'
14

          
15
Name: Barack Obama, Tweet: Stay Home! Stay Safe!
16
'Ajay' received notification from Handle: '#bobama', Tweet: 'Stay Home! Stay Safe!'
17
'Vijay' received notification from Handle: '#bobama', Tweet: 'Stay Home! Stay Safe!'
18
'Micheal' received notification from Handle: '#bobama', Tweet: 'Stay Home! Stay Safe!'
19
'Kim' received notification from Handle: '#bobama', Tweet: 'Stay Home! Stay Safe!'


Please note that when I unregistered 'Racheal' from Barak Obama's follower list, she stopped receiving notifications.

Please do not think that this is how the Tweeter works :) 

This is very small example to demonstrate the Observer Design Pattern structure, code and function.

Tweeter has an actual production system which is capable to maintain millions of followers for each user. So that does not suite this kind of synchronous notification method. There are many more components involve to make the tweeter operational.

That's all! I hope we are clear on implementation of Observer Design Pattern.

Source Code can be found here: Observer Design Pattern Sample Code 

I hope this tutorial demonstrates the use of command design pattern.

Liked the article? Please don't forget to press that like button. Happy coding!

Need more articles, please visit my profile: Brijesh Saxena.

Design Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Architecture and Code Design, Pt. 2: Polyglot Persistence Insights To Use Today and in the Upcoming Years
  • Double-Checked Locking Design Pattern in Java
  • Messaging Design Pattern (MDP) In Java

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!