观察者模式定义:对象之间多对一依赖的一种设计方案,被依赖的对象为Subject,依赖的对象为Observer,Subject通知Oberver变化。
观察者模式就像小时候的订牛奶业务
-
奶站:相当于Subject,负责订奶家庭的登记,派送,退订工作
-
用户:相当于Oberver,订奶家庭
Subject:负责用户的登记注册,移除和通知
Oberver:负责接收Subject的通知输入
代码案例:
1
2
3
4
5
6
|
//观察者
public
interface
Observer {
public
void
update();
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
class
MilkFamily
implements
Observer {
private
String familyName;
public
MilkFamily(String familyName) {
this
.familyName = familyName;
}
@Override
public
void
update() {
System.out.println(familyName+
"--------收到牛奶"
);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//被观察者
public
abstract
class
Observable {
protected
List<Observer> observerList =
new
ArrayList<Observer>();
//添加观察者
public
void
addObserver(Observer observer){
observerList.add(observer);
}
//移除观察者
public
void
deleteObserver(Observer observer){
observerList.remove(observer);
}
//通知所有观察者
public
void
notifyObservers(){
for
(Observer o : observerList){
o.update();
}
}
}
|
1
2
3
4
5
6
7
8
|
public
class
MileStation
extends
Observable {
public
void
deliver(){
System.out.println(
"新的一天到了,牛奶站准备送牛奶了。。。。。。"
);
super
.notifyObservers();
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
class
Main {
public
static
void
main(String args[]){
MileStation mileStation =
new
MileStation();
MilkFamily milkFamily =
new
MilkFamily(
"小小巫的家"
);
MilkFamily milkFamily2 =
new
MilkFamily(
"巫巫巫的家"
);
mileStation.addObserver(milkFamily);
mileStation.addObserver(milkFamily2);
mileStation.deliver();
}
}
|