打赏

Java模拟AWT事件监听器(Observer模式)

 观察者模式定义了一种一对多的依赖关系,让多个观察者同时监听一个被观察者,当被观察者发生变化,所有的观察者就做出及时的响应。GUI中的按钮(Button)的事件监听模式就是一个Observer模式的实现,现在我们通过模拟这个事件来理解Observer.

    对于Button的图形界面的事件,我们就通过在测试类模拟,而不模拟图形实现。

   

 1 interface Observerable {
 2     public void addActionListener(ActionListener a);
 3     public void pressed();
 4 }
 5 
 6 class Button implements Observerable{
 7     private List<ActionListener> l = new ArrayList<ActionListener>();
 8     
 9     public void addActionListener(ActionListener a) {
10         l.add(a);
11     }
12 
13     public void pressed() {
14         ActionEvent e = new ActionEvent(System.currentTimeMillis(), this);
15         for(int i=0; i<l.size(); i++) {
16             l.get(i).actionPerformed(e);
17         }
18     }
19     
20 }
21 
22 interface ActionListener {
23     void actionPerformed(ActionEvent e);
24 }
25 
26 class MyActionListener implements ActionListener {
27 
28     @Override
29     public void actionPerformed(ActionEvent e) {
30         System.out.println("MyActionListener");
31     }
32     
33 }
34 
35 class MyActionListener1 implements ActionListener {
36 
37     @Override
38     public void actionPerformed(ActionEvent e) {
39         System.out.println("MyActionListener1");
40     }
41     
42 }
43 
44 class ActionEvent {
45     private long when;
46     private Object o;
47     
48     public ActionEvent(long when, Object o) {
49         this.when = when;
50         this.o = o;
51     }
52     
53     public long getWhen() {
54         return when;
55     }
56     
57 }
58 public class Test {
59     
60     public static void main(String[] args) {
61         Observerable b = new Button();
62         b.addActionListener(new MyActionListener());
63         b.addActionListener(new MyActionListener1());
64         b.pressed();
65     }
66     
67 }

 

    类结构图大致如下:

 当Button事件发生变化时,每个Listener作出不同的响应,Observer模式的一个用的非常广的架构就是MVC,举个例子,如果直接在JSP页面连接数据库做数据操作,当数据结构进行更改时,整个JSP页面或许都得改,但如果采用MVC,我们只需要更改Model,对应的View就会发生改变,可见Observer允许独立的改变目标和观察者,我们可以单独的复用目标对象或者观察者对象,降低目标对象与观察者对象的耦合度。

posted @ 2013-04-20 22:12  lingjiango  阅读(1295)  评论(2编辑  收藏  举报