1,我们先定义一个接口,可以让多个监听者实现
1
2
3
4
|
public
interface
IDataListen {
public
void
update(Object event,Object msg);
}
|
2,实现一监听者
1
2
3
4
5
6
7
8
9
|
public
class
DataListen
implements
IDataListen{
@Override
public
void
update(Object event, Object arg) {
// TODO Auto-generated method stub
System.out.println(
"数据发生了变化"
);
}
}
|
3,被监听者
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
|
public
class
DataManager{
private
List<IDataListen> listenList =
new
ArrayList<>();
public
void
notifyListen(Object event,Object msg){
for
(IDataListen dataListen : listenList){
dataListen.update(
null
,
null
);
}
}
public
void
addListen(IDataListen dataListen){
listenList.add(dataListen);
}
public
void
updateData(Object msg){
this
.notifyListen(
null
, msg);
}
public
static
void
main(String[] args) {
DataManager dataManager =
new
DataManager();
IDataListen dataListen1 =
new
DataListen();
IDataListen dataListen2 =
new
DataListen();
dataManager.addListen(dataListen1);
dataManager.addListen(dataListen2);
dataManager.updateData(
"aaa"
);
}
}
|