觀察者模式(訂閱/發佈模式)
做者:
代碼大溼
代碼大溼java
Java中觀察者模式中主要是Observerable類(被觀察者),和Observer接口(觀察者)。下面是個簡單的demoide
//被觀察者this
package demo; import java.util.Observable; public class MyObserverable extends Observable{ //被觀察者調用了這個方法,觀察者就會發現 @Override protected synchronized void setChanged() { // TODO Auto-generated method stub super.setChanged(); } //被觀察者調用了這個方法,就會向觀察者發送改變的信息 @Override public void notifyObservers(Object arg) { // TODO Auto-generated method stub super.notifyObservers(arg); } }
//觀察者.net
package demo; import java.util.Observable; import java.util.Observer; public class MyObserver implements Observer{ private String name; public MyObserver(String name) { this.name=name; } //一旦被觀察者有改變,就會調用update方法 @Override public void update(Observable o, Object arg) { System.out.println(name+"觀察到 "+arg.toString()); } }
//main方法code
package demo; public class Main { public static void main(String[] args) { MyObserver myObserver_1=new MyObserver("observer_1"); MyObserver myObserver_2=new MyObserver("observer_2"); MyObserverable myObserverable=new MyObserverable(); //添加2個觀察者 myObserverable.addObserver(myObserver_1); myObserverable.addObserver(myObserver_2); String msg="msg has changed"; //設置消息改變點 myObserverable.setChanged(); //通知觀察者改變的消息 myObserverable.notifyObservers(msg); } }
結果server