Repository navigation
Expand file tree
/
Copy pathTest.java
More file actions
81 lines (62 loc) · 1.53 KB
/
Copy pathTest.java
File metadata and controls
81 lines (62 loc) · 1.53 KB
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
package com.feiyu.observer.v9;
import java.util.ArrayList;
import java.util.List;
/***
* 模拟Java本身的观察者模式
* @author feiyu
*
*/
public class Test {
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.actionPerformed(e);
}
}
public void addActionListener(ActionListener l) {
actionListeners.add(l);
}
}
interface ActionListener {
public void actionPerformed(ActionEvent e);
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("button pressed!");
}
}
class MyActionListener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("button pressed 2!");
}
}
/**
* 事件类
* @author feiyu
*
*/
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;
}
}