package cn.thought; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { Button btn = new Button(); btn.addActionListened(new MyListener()); btn.Pressed(); } } /** * 创建一个按钮内部维护监听器 * @author Administrator * */ class Button { /** * 对象的内部有个监听器集合 */ List<ActionListener> list = new ArrayList<ActionListener>(); /** * 当按钮被按下 */ public void Pressed() { for (ActionListener ac : list) { ac.actionPerformed(); } } /** * 为按钮添加监听器 * @param l */ public void addActionListened(ActionListener l) { this.list.add(l); } } /** * 实现监听器接口 * @author Administrator * */ class MyListener implements ActionListener { public void actionPerformed() { System.out.println("鼠标被按下了"); } } /** * 监听器接口 * @author Administrator * */ interface ActionListener { public void actionPerformed(); }