observer 的备忘(一)
在被监听的对象里添加一个List,其中保存着所有的ActionListener,ActionListener保留着当事件触发时的反应 ,当一个事件触发的时候就循环遍历所有的ActionListener调用触发方法,ActionEvent保留着一些时间发生的属性
package com.cht.observer.awt;import java.util.ArrayList;import java.util.List;public class MyAwtTest {public static void main(String[] args) { MyButton mb = new MyButton(); MyActionListener ma = new MyActionListener (); mb.addActionListener(new MyActionListener2()); mb.addActionListener(ma); mb.click(); }}class MyButton { //保留这个多个ActionListener的集合 private List<ActionListener> query = new ArrayList<ActionListener>(); public void click(){ //在单击事件初始化的时候,初始化ActionEvent对象 ActionEvent e = new ActionEvent(System.currentTimeMillis(),this); for(ActionListener a:query){ a.actionPerformed(e); } } public void addActionListener(ActionListener a ){ query.add(a); }}interface ActionListener {public void actionPerformed(ActionEvent e);}// ActionEvent 用于去记录一些事件发生的一些属性,例如时间,源对象等内容class ActionEvent {private long when;private Object source;ActionEvent(long w, Object source) {this.when = w;this.source = source;}public Object getSource() {return source;}public long getWhen() {return when;}}class MyActionListener implements ActionListener{@Overridepublic void actionPerformed(ActionEvent e) {System.out.println(e.getWhen()+ " in this side before or other");}}class MyActionListener2 implements ActionListener{@Overridepublic void actionPerformed(ActionEvent e) { System.out.println(e.getSource()+" Server ");}}