Observer Design Pattern in Java
Observer design pattern in Java is a basic core Java pattern where the Observer monitors any changes in the state or properties of the Subject . For example, a company updates all shareholders about any decision taken by them here the company is the subject and the shareholders are the observers, any changes in the company's policies and the company notifies all the shareholders or observers. This is a simple real world explanation of the observer pattern.
In this article, we will take a detailed look at what is observer design pattern , benefits of observer design pattern, examples or observer pattern in Java and a few other points. Just like decorator design pattern and factory pattern in Java, observer pattern is also used in JDK.
Observer Design Pattern Java Code Examples
Now, let's dive deeper into the observer design pattern and how to use it in the Java programming language:
By the way, to best understand design patterns, you need to develop some scenarios, examples, etc.
1. What is the Observer design pattern?
The observer design pattern in Java is a very important pattern, as the name suggests, it is used to observe things. Suppose we want to be notified of changes in a particular object, then we observe that object and notify the changes. The object being observed is called a Subject, and the class that observes the subject is called an Observer.
It is a beautiful pattern and is heavily used along with the Model View Controller design pattern, where changes to the model are propagated to the view so that it can present it with the modified information. The Observer pattern is also a very popular Java interview question that is mostly asked at an advanced or upper-intermediate level.
2. Problems solved by the observer pattern:
If we require a particular object to change its state and depending on this change some or a group of objects automatically change their state we need to implement observer pattern it will reduce coupling between objects. In real world if try to find example look at when a customer registers in this company we subscribe for new phone connection then all other departments get notified accordingly then based on the state do their job like verify their address then if customer state is verified send welcome kit etc.
How the Observer design pattern is implemented in Java;
For the implementation of this pattern, java makes our task very easy and developers do not need to do much to implement this pattern. In java.util
the package, we can find interfaces, classes, and methods that implement this pattern.
Public Interface Observer:
When the subject or observable object changes its state, any class implementing this interface must be notified.
Update (Observable Ob, Object arg)
: This method is called when the theme changes.
Observable class:
This is what the observer wants to observe.
Some important methods:
- addObserver(Observer o) : Adds Observers to the observer collection of this subject or observable object.
- deleteObserver(Observer o) : Deletes an observer from the observer collection.
- hasChanged() : Checks if the object has changed.
- clearChanged() : This method will indicate that the subject has not changed or that all observers have been notified when it changed.
- notifyObservers() : If the object changes, notify all observers.
Code example of observer design pattern in Java:
The Observer design pattern is more general than the way it is implemented in Java. We are free to choose java.util.Observable
or java.util.Observer
or write our own Subject and Observer interfaces. I prefer to have my own Subject and Observer interfaces and this is how I will write a code example of the Observer design pattern in java.
My example is very simple, there is a loan with an interest rate that may change, when it changes the loan notifies a newspaper or internet media to show the new loan rate.
To achieve this, we have a Subject interface, which contains methods for adding, removing, and notifying Observers, and an Observer interface, which contains update(int interest)
a method that will be called by the Subject implementation when the interest rate changes.
import java.util.ArrayList;
interface Observer {
public void update(float interest);
}
interface Subject {
public void registerObserver(Observer observer);
public void removeObserver(Observer observer);
public void notifyObservers();
}
class Loan implements Subject {
private ArrayList<Observer> observers = new ArrayList<Observer>();
private String type;
private float interest;
private String bank;
public Loan(String type, float interest, String bank) {
this.type = type;
this.interest = interest;
this.bank = bank;
}
public float getInterest() {
return interest;
}
public void setInterest(float interest) {
this.interest = interest;
notifyObservers();
}
public String getBank() {
return this.bank;
}
public String getType() {
return this.type;
}
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer ob : observers) {
System.out
.println("Notifying Observers on change in Loan interest rate");
ob.update(this.interest);
}
}
}
class Newspaper implements Observer {
@Override
public void update(float interest) {
System.out.println("Newspaper: Interest Rate updated, new Rate is: "
+ interest);
}
}
class Internet implements Observer {
@Override
public void update(float interest) {
System.out.println("Internet: Interest Rate updated, new Rate is: "
+ interest);
}
}
public class ObserverTest {
public static void main(String args[]) {
// this will maintain all loans information
Newspaper printMedia = new Newspaper();
Internet onlineMedia = new Internet();
Loan personalLoan = new Loan("Personal Loan", 12.5f,
"Standard Charterd");
personalLoan.registerObserver(printMedia);
personalLoan.registerObserver(onlineMedia);
personalLoan.setInterest(3.5f);
}
}
Advantages of Observer Design Pattern in Java:
The main advantage is the loose coupling between the observers and the observable. The subject only knows about the list of observers, it does not care how they are implemented. All observers are notified by the subject in a single event call as a broadcast communication
Disadvantages of Observer Design Pattern in Java:
- The downside is that sometimes if anything goes wrong, debugging becomes very difficult because the control flow is implicit between the observer and the observable, we can predict that now the observer will have an action, and if there is a chain between observers, debugging becomes more complicated.
- Another problem is memory management, because if we don't deregister the object, the subject will hold all the references of all the observers, which will create memory issues.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Store Div Id in PHP variable and pass it to JavaScript
Publish Date:2025/04/13 Views:51 Category:PHP
-
This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s
Use of Linux command at - set time to execute command only once
Publish Date:2025/04/08 Views:158 Category:OPERATING SYSTEM
-
This article mainly involves a knowledge point, which is the atd service. Similar to this service is the crond service. The functions of these two services can be similar to the two functional functions of javascript. Those who have learned
Design Patterns in Java - Visitor Pattern
Publish Date:2025/03/19 Views:175 Category:ALGORITHM
-
Today, we are going to learn one of the most useful patterns, the Visitor Pattern. What is the Visitor pattern? Well, let's look at an example. Let's say you're a software engineer working at a university. The university rarely has establis
How to use Strategy Pattern in Java?
Publish Date:2025/03/19 Views:142 Category:ALGORITHM
-
Hi everyone, you might have heard, “Can you tell me about any design pattern other than Singleton design pattern that you have used recently in your project?”. This is one of the popular questions in various Java interviews in recent ye
Difference between Proxy Mode and State Mode in Java
Publish Date:2025/03/19 Views:76 Category:ALGORITHM
-
Hi guys, if you are preparing for Java interview and looking for difference between Proxy and State design pattern, then you are at the right place. In the past, I have explained several important object-oriented design patterns like State,
Strategy Design Pattern and Open-Closed Principle in Java
Publish Date:2025/03/19 Views:114 Category:ALGORITHM
-
The Strategy design pattern is based on the Open/Closed design principle , the famous " O SOLID " of design principles . It is one of the patterns that has become popular in the field of object-oriented analysis and design, along with the D
How to implement binary search in Java without recursion?
Publish Date:2025/03/19 Views:198 Category:ALGORITHM
-
Hey Java programmers, if you want to implement binary search in Java and looking for iterative and recursive binary search algorithms, then you have come to the right place. Today I am going to teach you an important algorithm. In computer
How to implement the singleton pattern in JavaScript ES6+
Publish Date:2025/03/19 Views:55 Category:ALGORITHM
-
In this article, we will show you how to implement the singleton pattern in JavaScript. If we are a full-stack JavaScript developer, we know that JavaScript is a powerful language and we can build amazing websites with it. On the other hand
How to use the Adapter design pattern in Java
Publish Date:2025/03/19 Views:77 Category:ALGORITHM
-
The Adapter design pattern in Java , also known as the Wrapper pattern, is another very useful GOF pattern that helps bridge the gap between two classes in Java. According to the Gang of Four pattern list, Adapter is a structural pattern, m