标签:
package com.util.ObservDemoTest; import java.util.Observable; import java.util.Observer; public class ObservDemo extends Observable { MyView view; MyModel model; public ObservDemo() { view = new MyView(); model = new MyModel(); model.addObserver(view); System.out.println("1.初始化组件:\t"+"\n Observer:"+view +"\n Observable:"+model); } public static void main(String[] av) { ObservDemo me = new ObservDemo(); me.demo(); } public void demo() { System.out.println("2.对象发生变化。。。。"); model.changeSomething(); } /** The Observer normally maintains a view on the data */ class MyView implements Observer { /** For now, we just print the fact that we got notified. */ public void update(Observable obs, Object x) { System.out.print("4."); System.out.println("update(" + obs + "," + x + ");"); } } /** The Observable normally maintains the data */ class MyModel extends Observable { public void changeSomething() { // Notify observers of change System.out.println("**********************对象是否改变: "+hasChanged()+" ****************"); setChanged(); System.out.println("3.对象是否改变 "+hasChanged()+" ,调用观察者的update方法:"); notifyObservers(); } } }
运行结果:
/******************** 测试2 *********************/
package com.util.ObservDemoTest; import java.util.Observable; import java.util.Observer; public class ObservDemo extends Observable { MyView view; MyModel model; public ObservDemo() { view = new MyView(); model = new MyModel(); model.addObserver(view); System.out.println("1.初始化组件:\t"+"\n Observer:"+view +"\n Observable:"+model); } public static void main(String[] av) { ObservDemo me = new ObservDemo(); me.demo(); } public void demo() { System.out.println("2.对象发生变化。。。。"); model.changeSomething(); } /** The Observer normally maintains a view on the data */ class MyView implements Observer { /** For now, we just print the fact that we got notified. */ public void update(Observable obs, Object x) { System.out.print("4."); System.out.println("update(\n " + obs + ",\n " + x + "\n );"); } } /** The Observable normally maintains the data */ class MyModel extends Observable { public void changeSomething() { // Notify observers of change System.out.println("**********************对象是否改变: "+hasChanged()+" ****************"); setChanged(); System.out.println("3.对象是否改变 "+hasChanged()+" ,调用观察者的update方法:"); model = new MyModel(); notifyObservers(model); } } }运行结果:
/**************************************** 补充 *****************************************/
标签:
原文地址:http://my.oschina.net/u/1989867/blog/517871