Java中自带Observer模式运用
使用Java中自带的Observer模式时,需要用到一下两个类:
import java.util.Observable;import java.util.Observer;public class TfObserver implements Observer{@Overridepublic void update(Observable arg0, Object arg1){System.out.println("Tf's Observer has saved " + arg1);}}?
MhObserver.java
import java.util.Observable;import java.util.Observer;public class MhObserver implements Observer{@Overridepublic void update(Observable o, Object arg){System.out.println("Mh's Observer has saved " + arg);}}
?以上为两个观察者。
?
Client.java
import java.util.Observable;public class Client extends Observable{public void notifyAll(String s){super.setChanged();super.notifyObservers(s);}}
?需注册观察者的Client。
?MainClass.java
import java.util.Observer;public class MainClass{public static void main(String[] args){Client o = new Client();Observer tf = new TfObserver();Observer mh = new MhObserver();o.addObserver(tf);o.addObserver(mh);//System.out.println(o.countObservers());//只有在setChange()被调用后,notifyObservers()才会去调用update(),否则什么都不干。//System.out.println(o.hasChanged());o.notifyAll("Lol~");}}?
?