首页 > 代码库 > 观察者设计模式例子

观察者设计模式例子

1.被观察对象

package 观察者设计模式;import java.util.Observable;//被观察者对象public class ObserverObject extends Observable {    public String toString()    {        return "张小二";            }    public void sentMessage(String s)    {        this.setChanged();        this.notifyObservers(s);    }        }

2.被观察对象

package 观察者设计模式;import java.util.Observable;import java.util.Observer;public class Observer1  implements Observer{    public void update(Observable arg0, Object arg1) {                System.out.println("Observer1 receive " +arg1+" from "+arg0);                    }}package 观察者设计模式;import java.util.Observable;import java.util.Observer;public class Observer2 implements Observer{    public void update(Observable o, Object arg) {        // TODO Auto-generated method stub        System.out.println( "observer2 "+"received "+arg+"  from "+o);            }}

3.主类

 

package 观察者设计模式;public class Main {    public static void main(String[] args) {        // TODO Auto-generated method stub        ObserverObject obj=new ObserverObject();        Observer1 osv=new Observer1();        Observer2 osv2=new Observer2();        obj.addObserver(osv);        obj.addObserver(osv2);        obj.sentMessage("hello");            }}

 

观察者设计模式例子