import java.util.List; |
import java.util.ArrayList; |
/** |
* 观察者(observer)模式:模拟java.awt.Button事件监听。 |
*/ |
public class Test { |
public static void main(String[] args) { |
Button btn1 = new Button( "第一个按钮" ); |
Button btn2 = new Button( "第二个按钮" ); |
// 为第一个按钮添加监听器 |
btn1.addActionListener( new ActionListener() { |
@Override |
public void actionPerformed(ActionEvent e) { |
System.out.println(e.getName() + "被点击" ); |
} |
}); |
// 为第二个按钮添加监听器 |
btn2.addActionListener( new ActionListener() { |
@Override |
public void actionPerformed(ActionEvent e) { |
System.out.println(e.getName() + "被点击" ); |
} |
}); |
// 模拟点击事件 |
btn1.click(); |
btn2.click(); |
} |
} |
class Button { |
private String name = null ; |
private List<ActionListener> actionlisteners = new ArrayList<ActionListener>(); |
public Button(String name) { |
this .name = name; |
} |
public void click() { |
ActionEvent e = new ActionEvent( this .name); |
for ( int i = 0 ; i < actionlisteners.size(); i++) { |
ActionListener l = actionlisteners.get(i); |
l.actionPerformed(e); |
} |
} |
public void addActionListener(ActionListener e) { |
actionlisteners.add(e); |
} |
} |
/* |
* 监听器接口 |
*/ |
interface ActionListener { |
public void actionPerformed(ActionEvent e); |
} |
/* |
* 事件源类 |
*/ |
class ActionEvent { |
private String name; |
public ActionEvent(String name) { |
this .name = name; |
} |
public String getName() { |
return name; |
} |
} |