-
Notifications
You must be signed in to change notification settings - Fork 7
/
ObserverPattern.java
134 lines (108 loc) · 2.57 KB
/
ObserverPattern.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package observer_design_pattern;
import java.util.ArrayList;
import java.util.List;
interface Subject
{
void register(Observer obj);
void unregister(Observer obj);
void notifyObservers();
}
class DeliveryData implements Subject
{
private List<Observer> observers;
private String location;
public DeliveryData()
{
this.observers = new ArrayList<>();
}
@Override
public void register(Observer obj)
{
observers.add(obj);
}
@Override
public void unregister(Observer obj)
{
observers.remove(obj);
}
@Override
public void notifyObservers()
{
for(Observer obj : observers)
{
obj.update(location);
}
}
public void locationChanged()
{
this.location = getLocation();
notifyObservers();
}
public String getLocation()
{
return "YPlace";
}
}
interface Observer
{
public void update(String location);
}
class Seller implements Observer
{
private String location;
@Override
public void update(String location)
{
this.location = location;
showLocation();
}
public void showLocation()
{
System.out.println("Notification at Seller - Current Location: " + location);
}
}
class User implements Observer
{
private String location;
@Override
public void update(String location)
{
this.location = location;
showLocation();
}
public void showLocation()
{
System.out.println("Notification at User - Current Location: " + location);
}
}
class DeliveryWarehouseCenter implements Observer
{
private String location;
@Override
public void update(String location)
{
this.location = location;
showLocation();
}
public void showLocation()
{
System.out.println("Notification at Warehouse - Current Location: " + location);
}
}
public class ObserverPattern
{
public static void main(String[] args)
{
DeliveryData topic = new DeliveryData();
Observer obj1 = new Seller();
Observer obj2 = new User();
Observer obj3 = new DeliveryWarehouseCenter();
topic.register(obj1);
topic.register(obj2);
topic.register(obj3);
topic.locationChanged();
topic.unregister(obj3);
System.out.println();
topic.locationChanged();
}
}