1、花与蜜蜂
一朵花有Open和Close两种状态,3只蜂鸟在花Open的时候去采蜜,在花Close的时候要回巢,用面向对象技术和Design Pattern方法模拟上面过程,输出如下:
1 | Flow Open |
要求:
- 1)使用一种Design Pattern方法,使花和蜜蜂之间松耦合,用你最熟悉的计算机语言写出上面完整程序;
- 2)画出UML类图。
2、分析
- 1、花只有一朵,但有不同状态
- 2、蜜蜂有N只,且根据花的状态不同来通知蜜蜂实现不同的行为
所以可以判断为明显的一对多的观察者模式
3、实现
1)被观察者 - 花
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import java.util.Observable;
public class Flower extends Observable {
public static final String Flow_Open = "Flow Open";
public static final String Flow_Close = "Flow Close";
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
super.setChanged();
this.status = status;
System.out.println(status);
//通知所有观察者
notifyObservers(status);
}
}2)观察者 - 蜜蜂
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24import java.util.Observable;
import java.util.Observer;
public class Hummingbird implements Observer {
private String name;
public Hummingbird(String name) {
// TODO Auto-generated constructor stub
this.name = name;
}
@Override
public void update(Observable observable, Object data) {
// TODO Auto-generated method stub
String status = data.toString();
if (Flower.Flow_Open.equals(status)) {
System.out.println(name + " breakfast time!");
} else {
System.out.println(name + " bed time!");
}
}
}3)测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public class Test {
public static void main(String[] args) {
Flower flower = new Flower();
Hummingbird hummingbird1 = new Hummingbird("Hummingbird 1’s");
flower.addObserver(hummingbird1);
Hummingbird hummingbird2 = new Hummingbird("Hummingbird 2’s");
flower.addObserver(hummingbird2);
Hummingbird hummingbird3 = new Hummingbird("Hummingbird 3’s");
flower.addObserver(hummingbird3);
flower.setStatus(Flower.Flow_Open);
flower.setStatus(Flower.Flow_Close);
}
}