- 观察者接口:Observer接口、Listener接口、Hook、Callback
- 具体观察者:实现Observer接口
- 事件类 :不仅仅包含时间,事件,还包含事件源。这样观察者拿到事件知道是谁发的才可以做有区别的处理
- 事件源对象:被观察者Object,

事件源对象,新建事件对象。事件源自己会维护很多监听器。可以调用监听器接口的方法,
**事件对象 **穿过 Observer的链条
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
| package com.deltaqin.designPattern.d09_observer;
import java.util.ArrayList; import java.util.List;
public class Demo { public static void main(String[] args) { Button b = new Button(); b.addActionListener(new MyActionListener()); b.addActionListener(new MyActionListener2()); b.buttonPressed(); } }
class Button {
private List<ActionListener> actionListeners = new ArrayList<ActionListener>();
public void buttonPressed() { ActionEvent e = new ActionEvent(System.currentTimeMillis(),this); for(int i=0; i<actionListeners.size(); i++) { ActionListener l = actionListeners.get(i); l.notify(e); } }
public void addActionListener(ActionListener l) { actionListeners.add(l); } }
interface ActionListener { public void notify(ActionEvent e); }
class MyActionListener implements ActionListener {
public void notify(ActionEvent e) { System.out.println("button pressed!"); }
}
class MyActionListener2 implements ActionListener {
public void notify(ActionEvent e) { System.out.println("button pressed 2!"); }
}
class ActionEvent {
long when; Object source;
public ActionEvent(long when, Object source) { super(); this.when = when; this.source = source; }
public long getWhen() { return when; }
public Object getSource() { return source; }
}
|