设计模式应用场景
一个对象的改变将导致或者需要导致其他一个或多个对象也发生改变
实现方式
1.创建实体类参数
class ActionEvent {long when;Object source;public ActionEvent(long when, Object source) {this.when = when;this.source = source;}
}
2.创建监听器接口(监听器即为观察者)
interface ActionListener{void actionPerformed(ActionEvent e);
}
3.创建监听器具体实现
class ButtonListenerOne implements ActionListener{@Overridepublic void actionPerformed(ActionEvent e) {System.out.println("One:::" + e.when +":::"+ e.source.toString());}
}class ButtonListenerTwo implements ActionListener{@Overridepublic void actionPerformed(ActionEvent e) {System.out.println("Two:::" + e.when +":::"+ e.source.toString());}
}
4.创建被监听者(被观察者)
其中需要添加监听器的方法addListeners和执行方法buttonPressed
在buttonPressed需要将我们自身作为参数传给观察者
class Button{private List<ActionListener> Listeners &#61; new ArrayList<ActionListener>();public void addListeners(ActionListener listener){this.Listeners.add(listener);}public void buttonPressed() {ActionEvent e &#61; new ActionEvent(System.currentTimeMillis(),this);for(int i&#61;0; i<Listeners.size(); i&#43;&#43;) {ActionListener l &#61; Listeners.get(i);l.actionPerformed(e);}}&#64;Overridepublic String toString() {return "Button{" &#43;"Listeners&#61;" &#43; Listeners &#43;&#39;}&#39;;}
}
5.测试
public static void main(String[] args) {Button b &#61; new Button();b.addListeners(new ButtonListenerOne());b.addListeners(new ButtonListenerTwo());b.buttonPressed();}
结果