Skip to content

Commit ffdbcab

Browse files
committed
Observer Design Pattern - Bonus example - Java api implementation
1 parent 98b6e80 commit ffdbcab

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.premaseem;
2+
/*
3+
@author: Aseem Jain
4+
@title: Design Patterns with Java 9
5+
@link: https://premaseem.wordpress.com/category/computers/design-patterns/
6+
*/
7+
8+
import java.util.Observable;
9+
import java.util.Observer;
10+
import java.util.Scanner;
11+
12+
public class ClientJavaApi {
13+
14+
public static void main(String[] args) {
15+
16+
// Created subject
17+
Subject subject = new Subject();
18+
19+
// Created Observer
20+
Observer observer = new Observer() {
21+
public void update(Observable obj, Object arg) {
22+
System.out.println("Observer notified with update: " + arg);
23+
}
24+
};
25+
26+
// registered observer to the subject
27+
subject.addObserver(observer);
28+
29+
System.out.println("Make text updates in subject: ");
30+
new Thread(subject).start();
31+
}
32+
}
33+
34+
class Subject extends Observable implements Runnable {
35+
public void run() {
36+
37+
// Every time whenever there is an update in subject,
38+
// observer will be notified
39+
while (true) {
40+
String update = new Scanner(System.in).next();
41+
setChanged();
42+
notifyObservers(update);
43+
}
44+
}
45+
}
46+
47+
/** Lesson Learnt
48+
*
49+
* 1. Instead of creating our own observer and observable,
50+
* using (java.util) Java api's implementation of observer and observable
51+
*
52+
* 2. Java 9 has deprecated above apis, WHY ?
53+
* answer is in link -https://stackoverflow.com/questions/46380073/observer-is-deprecated-in-java-9-what-should-we-use-instead-of-it
54+
* */

0 commit comments

Comments
 (0)