轻松理解设计模式——观察者模式

观察者模式,学习代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.kevinlsui.observer.example;
/**
* 被观察类接口
*/
public interface Subject {
// 观察者注册
public void add(Observer o);
//观察者注销
public void remove(Observer o);
// 消息发布
public void update();
}
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
package com.kevinlsui.observer.example;
import java.util.ArrayList;
import java.util.List;
/**
* 被观察类
*/
public class WeatherData implements Subject{
private int low;
private int hight;
private String weather;
private List<Observer> list = new ArrayList<Observer>();
public int getLow() {
return low;
}
public int getHight() {
return hight;
}
public String getWeather() {
return weather;
}
public void setData(int low,int hight,String weather){
this.low = low;
this.hight = hight;
this.weather = weather;
update();
}
@Override
public void add(Observer o) {
if(!list.contains(o)){
list.add(o);
}
}
@Override
public void remove(Observer o) {
if(list.contains(o)){
list.remove(o);
}
}
@Override
public void update() {
for(Observer o :list){
o.update(getLow(),getHight(),getWeather());
}
}
}
1
2
3
4
5
6
7
8
9
package com.kevinlsui.observer.example;
/**
* 观察类接口
*/
public interface Observer {
//坐等信息发布过来
public void update(int low,int hight,String weather);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.kevinlsui.observer.example;
/**
* 观察类1
*/
public class Ipad implements Observer{
private Subject sub;
public Ipad(Subject subject){
this.sub = subject;
subject.add(this);
}
public void cancle(){
sub.remove(this);
}
@Override
public void update(int low, int hight, String weather) {
System.out.println("Ipd....low:"+low+";hight:"+hight+";weather:"+weather);
}
}
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
package com.kevinlsui.observer.example;
/**
* 观察类2
*/
public class Phone implements Observer{
private Subject sub;
public Phone(Subject subject){
this.sub = subject;
subject.add(this);
}
public void cancle(){
sub.remove(this);
}
@Override
public void update(int low, int hight, String weather) {
System.out.println("Phone..........low:"+low+";hight:"+hight+";weather:"+weather);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.kevinlsui.observer.example;
/**
*测试类
*/
public class Test {
public static void main(String[] args) {
System.out.println("观察者模式.........");
WeatherData we = new WeatherData();
Phone p = new Phone(we);
Ipad ipad = new Ipad(we);
we.setData(1, 12, "晴天");
p.cancle();
we.setData(5, 18, "大晴天");
}
}
文章目录
|