-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathObserverPattern
76 lines (58 loc) · 1.71 KB
/
ObserverPattern
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.ArrayList;
import java.util.List;
public class ObserverPattern {
public static void main(String[] args){
WayneIndustries wayneIndustries = new WayneIndustries();
wayneIndustries.subscribeObserver(new Superhero("Batman"));
wayneIndustries.subscribeObserver(new Superhero("Robin"));
wayneIndustries.addWeapon("Batarang");
wayneIndustries.addWeapon("Batman's utility belt");
}
}
interface Subject {
void subscribeObserver(Observer observer);
void unsubscribeObserver(Observer observer);
void notifyAllObserver();
}
interface Observer {
void update(Subject subject);
}
class WayneIndustries implements Subject {
List<Observer> observerList;
List<String> weaponsList;
WayneIndustries(){
observerList = new ArrayList<Observer>();
weaponsList = new ArrayList<String>();
}
public void subscribeObserver(Observer observer) {
observerList.add(observer);
}
public void unsubscribeObserver(Observer observer) {
observerList.remove(observer);
}
public void notifyAllObserver() {
for(Observer observer: observerList){
observer.update(this);
}
}
public void addWeapon(String weapon){
weaponsList.add(weapon);
notifyAllObserver();
}
public List<String> getWeapon(){
return weaponsList;
}
public String toString(){
return weaponsList.toString();
}
}
class Superhero implements Observer {
private String name;
Superhero(String name){
this.name = name;
}
public void update(Subject subject) {
System.out.println(this.name + " got notified");
System.out.println(subject);
}
}