/** Java观察者模式的场景:一个女孩洗澡,被很多男孩偷看。 女孩洞察后,搜索坏男孩,然后继续洗澡。 三个类:Boy,Girl还有主类MainClass。 */ /* 男孩 Boy.java */ import java.util.Observable; import java.util.Observer; public class Boy implements Observer{ private String name=""; public Boy(String name){ this.name=name; } @Override public void update(Observable o, Object obj) { Girl girl=(Girl)o; System.out.println(name+" 看到 "+girl.getName()+" "+girl.getStatus()); } public String getName() { return name; } } /* 女孩 Girl.java */ import java.util.Observable; public class Girl extends Observable{ private String name=""; private String thing=""; public Girl(String name){ this.name=name; } public void doSomething(String thing){ this.thing=thing; this.setChanged(); this.notifyObservers(thing); } public String getStatus(){ return thing; } public String getName(){ return name; } } /* 主类,测试 */ import java.util.ArrayList; import java.util.Random; public class MainClass { private Girl girl=null; private ArrayList<Boy> boys=new ArrayList<Boy>(); public MainClass() { girl=new Girl("MM"); Boy boyA=new Boy("小A"); Boy boyB=new Boy("小B"); Boy boyC=new Boy("小C"); Boy boyD=new Boy("小D"); boys.add(boyA); boys.add(boyB); boys.add(boyC); boys.add(boyD); girl.addObserver(boyA); girl.addObserver(boyB); girl.addObserver(boyC); girl.addObserver(boyD); girl.doSomething("脱衣服..."); girl.doSomething("洗澡..."); girl.doSomething("感觉有人偷看!?停止洗澡,穿上衣服,开始搜查..."); girlSearchBadBoy(); //搞定!继续洗澡 girl.doSomething("再次脱衣服..."); girl.doSomething("再次洗澡..."); } private void girlSearchBadBoy() { Random rand=new Random(); int unluckyNumber=rand.nextInt( girl.countObservers() ); Boy unluckyBoy=boys.get(unluckyNumber); System.out.println(unluckyBoy.getName()+" 暴露,踢出去!"); girl.deleteObserver(unluckyBoy); } public static void main(String[] args) { new MainClass(); } }
Java观察者模式 : Observer / Observable
原文:http://blog.csdn.net/zhangphil/article/details/43767395