- Observable is a class.
- Observer is an interface.
- Observable class maintains a list of observers.
- If something changes in Observable then it will notify all its observers.
import java.util.Observable;
import java.util.Observer;
class NewPosts extends Observable {
private String post;
public String getPost() {
return post;
}
public void updatePost(String post) {
this.post = post;
setChanged();
notifyObservers(post);
}
public static void main(String[] args) {
NewPosts posts = new NewPosts();
User user1 = new User();
User user2 = new User();
posts.addObserver(user1);
posts.addObserver(user2);
board.updatePost("New Post is available");
}
}
class User implements Observer {
public void update(Observable o, Object arg) {
System.out.println("New Post available: " + arg);
}
}
In the above example, a user registers by adding himself to the list of observers. When a new post is available, the user will be notified. Similarly, when a new post is available the observable updates all the users in the observers list.
You might also like:
Java Concepts
Java String concepts
Immutable classes in Java
Remove duplicates from the array
Telephonic phone technical interview questions
Telephonic phone technical interview questions - Part 2
Serialization & Deserialization
Jersey Package Dependencies
Servlet Filter
Servlet Client Request
Spring dependencies for Maven
Java String Operations
No comments:
Post a Comment