设计模式学习(十八) 观察者模式
场景:
-- 网站上,很多人订阅了“java主题”的新闻,当有这个主题新闻时,就会将这些新闻发给所有订阅的人。
我们可以把多个订阅者,客户称之为观察者,需要同步给多个订阅者的数据封装到对象中,称之为目标
核心:
-- 观察者模式主要用于1:N 的通知。当一个对象(目标对象Subject或Objservable)的状态变化时,他需要及时告知一系列对象(观察者对象,Observer)
令他们做出响应
-- 通知观察者的方式;
推:
-- 每次都会把通知以广播方式发送给所有观察者,所有观察者只能被动接收函
拉:
-- 观察者只要直到有情况即可。至于什么时候获取内容,获取什么内容,都可以自主决定。
代码一:
package com.lp.obderver; public interface Observer { void update(Subject s); }
package com.lp.obderver; public class ObserverA implements Observer{ private int myState;//这里的值要与subject的值一样 @Override public void update(Subject s) { myState = ((ConcreteSubject)s).getState(); } public int getMyState() { return myState; } public void setMyState(int myState) { this.myState = myState; } }
package com.lp.obderver; import java.util.ArrayList; import java.util.List; public class Subject { protected List<Observer> list = new ArrayList<Observer>(); public void registerObserver(Observer obs){ list.add(obs); } public void removerObserver(Observer obs){ list.remove(obs); } //通知所有观察者改变状态 public void notifyAllObservers(){ for(Observer obs : list){ obs.update(this); } } }
package com.lp.obderver; public class ConcreteSubject extends Subject{ private int state; public int getState() { return state; } public void setState(int state) { this.state = state; this.notifyAllObservers(); } }
package com.lp.obderver; public class Client { public static void main(String[] args){ //目标对象 ConcreteSubject subject = new ConcreteSubject(); //创建多个观察者 ObserverA obs1 = new ObserverA(); ObserverA obs2 = new ObserverA(); ObserverA obs3 = new ObserverA(); subject.registerObserver(obs1); subject.registerObserver(obs2); subject.registerObserver(obs3); subject.setState(100); System.out.println(obs1.getMyState()); System.out.println(obs2.getMyState()); System.out.println(obs3.getMyState()); } }
代码二:
使用JAVASE提供的java.util.Observable类和java.util.Observer 来实现观察者模式
package observer2; import java.util.Observable; public class ConcreteSubject extends Observable{ private int state; public int getState() { return state; } public void setState(int state) { this.state = state; } public void set(int s){ state = s; setChanged();//表示目标对象已经做了更改 notifyObservers(state); // 通知所有的观察者 } }
package observer2; import java.util.Observable; import java.util.Observer; public class ObserverA implements Observer{ private int myState; @Override public void update(Observable o, Object arg) { myState = ((ConcreteSubject)o).getState(); } public int getMyState() { return myState; } public void setMyState(int myState) { this.myState = myState; } }
package observer2; public class Client { public static void main(String[] args){ ConcreteSubject subject = new ConcreteSubject(); ObserverA obs1 = new ObserverA(); ObserverA obs2 = new ObserverA(); ObserverA obs3 = new ObserverA(); subject.addObserver(obs1); subject.addObserver(obs2); subject.addObserver(obs3); subject.set(100); System.out.println(obs1.getMyState()); System.out.println(obs2.getMyState()); System.out.println(obs3.getMyState()); } }
类图:
实现场景