zoukankan      html  css  js  c++  java
  • 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允许独立的改变目标和观察者,我们可以单独的复用目标对象或者观察者对象,降低目标对象与观察者对象的耦合度。

  • 相关阅读:
    Medium | LeetCode 142. 环形链表 II
    Easy | LeetCode 141. 环形链表
    Hard | LeetCode 23. 合并K个升序链表 | 分治 | 优先队列
    std(19)内置算法find find_if
    stl(18)内置算法for_each transform
    C++引用和指针比较 指针常量和常量指针
    #pragma once和#ifndef用法
    c++变量的一些注意点 extern关键字的使用
    比特 字节 地址 类型 编码 32位 64位
    stl(16)stl内置的一些函数对象
  • 原文地址:https://www.cnblogs.com/iou123lg/p/3033217.html
Copyright © 2011-2022 走看看