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
Java Decorator Design Pattern Example
Publish Date:2025/03/19 Views:115 Category:ALGORITHM
-
Hello everyone, if you want to learn about Decorator Design Pattern in Java , then you have come to the right place. As design patterns are very important while building software and equally important in any core Java interview, it is alway
How to use Composite Design Pattern in Java?
Publish Date:2025/03/19 Views:179 Category:ALGORITHM
-
Hello Java programmers, if you want to learn about Composite Design Pattern in Java , such as how to implement Composite Design Pattern and when to use it, then you have come to the right place. In this article, we will discuss Composite De
How to find the IP address of the local host in Java
Publish Date:2025/03/17 Views:98 Category:NETWORK
-
The Java Networking API provides a way to find the local host IP address from a Java program using the java.net InetAddress class. It is rare that you need the local host IP address in a Java program. Most of the time, I use the Unix command to find t
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:58 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Do you understand JavaScript closures?
Publish Date:2025/02/21 Views:111 Category:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
Publish Date:2025/02/21 Views:183 Category:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
Publish Date:2025/02/21 Views:156 Category:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
Publish Date:2024/03/23 Views:89 Category:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。
如何检查 JavaScript 中的变量是否为字符串
Publish Date:2024/03/23 Views:159 Category:JavaScript
-
本教程介绍了如何在 JavaScript 中检查变量是否为字符串。