标签:
在Java中通过Observable类和Observer接口实现了观察者模式。实现Observer接口的对象是观察者,继承Observable的对象是被观察者。
void addObserver(Observer o)
|
setChanged();
notifyObservers();
|
void update(Observable o, Object arg)
|
package designpattern_observer; import java.util.Observable; public class MyButtonObserable extends Observable { private String clickMode; public String getClickMode() { return clickMode; } public void setClickMode(String clickMode) { this.clickMode = clickMode; this.setChanged(); this.notifyObservers(clickMode); } }
package designpattern_observer; import java.util.Observable; import java.util.Observer; public class MyTextBoxAbserver implements Observer { @Override public void update(Observable o, Object arg) { if (arg.toString().equals("double clicked")) { System.out.println("你对按钮执行了双击操作."); } } }
Test类:
package designpattern_observer; public class ObserverTest { public static void main(String[] args) { MyButtonObserable button = new MyButtonObserable(); MyTextBoxAbserver textbox = new MyTextBoxAbserver(); button.addObserver(textbox); button.setClickMode("double clicked"); } }
执行入口函数,调用 button.setClickMode("double clicked"),则触发MyTextBoxAbserver 对象的update方法,打印输出:
你对按钮执行了双击操作.
Java中使用Observer接口和Observable类实践Observer观察者模式
标签:
原文地址:http://www.cnblogs.com/franson-2016/p/5569371.html