Java-马士兵设计模式学习笔记-观察者模式-模拟Awt Button

时间:2023-03-08 18:32:58
Java-马士兵设计模式学习笔记-观察者模式-模拟Awt Button

一、概述

Java 的Awt是 Observer模式,现用Java自己模拟awt中Button的运行机制

二、代码

1.Test.java

 import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; public class Test { public static void main(String[] args) {
Button b = new Button();
b.addActionListener(new MyActionListener1());
b.addActionListener(new MyActionListener2());
b.buttonPress();
}
} class Button { //用List存放Listener
private List<ActionListener> actionListeners = new ArrayList<ActionListener>(); public void addActionListener(ActionListener l) {
actionListeners.add(l);
} public void buttonPress(){
ActionEvent e = new ActionEvent(System.currentTimeMillis(), this);
for (ActionListener l : actionListeners) {
l.actionPerformed(e);
}
}
} interface ActionListener {
public void actionPerformed(ActionEvent e);
} class MyActionListener1 implements ActionListener { @Override
public void actionPerformed(ActionEvent e) {
System.out.println("MyActionListener1");
System.out.println("事件发生时间:"+e.getTime()+" 事件源:"+e.getSource());
} } class MyActionListener2 implements ActionListener { @Override
public void actionPerformed(ActionEvent e) {
System.out.println("MyActionListener2");
System.out.println("事件发生时间:"+e.getTime()+" 事件源:"+e.getSource()); } } class ActionEvent { private long time;
private Object source; public ActionEvent(long time, Object source) {
this.time = time;
this.source = source;
} public Object getSource() {
return source;
} public String getTime() {
// DateFormat df = new SimpleDateFormat("dd:MM:yy:HH:mm:ss");
DateFormat df = new SimpleDateFormat("yyyy:MM:dd---HH:mm:ss");
return df.format(new Date(time));
} }

三、运行结果

Java-马士兵设计模式学习笔记-观察者模式-模拟Awt Button