直接上代碼
java
package yct.com.watcher.test; import yct.com.watcher.Watched; import yct.com.watcher.impl.BoyWatched; import yct.com.watcher.impl.BoyWatcher; import yct.com.watcher.impl.GrilWatcher; /** * 觀察者模式測試類 * @author 哥帥 * weixin:YangCongTou8023 */ public class WatcheTest { public static void main(String[] args) { //被觀察者 Watched boyWatched=new BoyWatched(); //觀察者 GrilWatcher grilWatcher=new GrilWatcher(); //觀察者 BoyWatcher boyWatcher=new BoyWatcher(); //添加觀察者到被觀察者的集合中 boyWatched.add(boyWatcher); boyWatched.add(grilWatcher); //被觀察者通知觀察者 boyWatched.notifyWatchers(" 我從泰國回來啦!"); } }
打印結果:測試
BoyWatched:我是男的!code
我從泰國回來啦!接口
BoyWatcher:我還愛你。。rem
GrilWatcher:我也要去!class
---------------下面是具體代碼test
定義一個被觀察者接口,一個觀察者接口
import
package yct.com.watcher; /** * 觀察者接口 * @author 哥帥 * weixin:YangCongTou8023 */ public interface Watched { //可添加觀察者 public void add(Watcher watcher); //可刪除觀察者 public void delete(Watcher watcher); //通知觀察者 public void notifyWatchers(String msg); }
package yct.com.watcher; /** * 觀察者接口 * @author 哥帥 */ public interface Watcher { //要執行的動做 public void update(); }
定義一個具體的被觀察者類,兩個具體的觀察者類date
package yct.com.watcher.impl; import java.util.ArrayList; import java.util.List; import yct.com.watcher.Watched; import yct.com.watcher.Watcher; public class BoyWatched implements Watched{ //觀察者集合 List<Watcher> watchers=new ArrayList<Watcher>(); //構造器 public BoyWatched(){ System.out.println("BoyWatched:我是男的!"); } //添加觀察者 public void add(Watcher watcher) { watchers.add(watcher); } //刪除觀察者 public void delete(Watcher watcher) { watchers.remove(watcher); } //通知觀察者 public void notifyWatchers(String msg) { System.out.println(msg); for(Watcher watcher:watchers){ watcher.update(); } } }
package yct.com.watcher.impl; import yct.com.watcher.Watcher; /** * 定義一個具體的觀察者(boyWatcher) * @author 哥帥 * weixin:YangCongTou8023 */ public class BoyWatcher implements Watcher{ public void update() { System.out.println("BoyWatcher:我還愛你。。"); } }
package yct.com.watcher.impl; import yct.com.watcher.Watcher; /** * 定義一個具體的觀察者(grilWatcher) * @author 哥帥 * weixin:YangCongTou8023 */ public class GrilWatcher implements Watcher{ public void update() { System.out.println("GrilWatcher:我也要去!"); } }
這就是最簡單的觀察者模式,觀察者模式有分推模型和拉模型,以上代碼屬於推模型。只須要被觀察者的通知方法將本身做爲參數便可,這要觀察者能夠經過此參數主動獲取數據,即「拉」。
List
有寫錯的地方望指教!