设计模式-观察者模式
- 观察者模式详解
- 观察者模式在android中的实际运用

11-8_11章结束[00_57_56][20180806-202807-1].jpg
1.观察者模式详解
1.概念
2.使用场景
3.UML结构图分析
4.实际代码分析
5.观察者模式的优点
1.概念
1.定义对象之间的一种一对多依赖关系,使得每当一个对象状态发生改变时其相关以来对象皆得到通知并自动更新
2.使用场景
1.一个抽象模型有两个方面,其中一个方面依赖于另一个方面
2.一个对象的改变将导致一个或者多个其他对象也发生改变
3.需要在系统中创建一个出触发链:A对象影响B ,B影响C
3.UML结构图分析
图:
Subject:方法attach(Observer obs)、detach(Observer obs)、notify()
抽象主题类:被观察的角色,它把所有的观察者对象引用保存在集合里,每一个Subject都有任意数量的观察者
ConcreteSubject:具体的主题,将有关状态存入具体对象中,
-subjectState-->属性 、方法 +getState()、+setState()
Observer: 方法 +update()
ConcreteObserver: -observerState;--->subject.getState()
+update();//得到通知,改变自己
4.实际代码分析
图:
第一种写法:
将观察者对象 设置到被观察者对象的集合中,触发某个条件后,被观察者调用notify即 遍历调用观察者的update方法
第二种写法:java 内置的
图:
Observer 接口:
void update(Object o,Object arg)
Observable
private boolean changed = false;
private Vector<Observer> obs;
public Observable(){
obs = new Vector();
}
public synchronized void addObserver(Observer o){
if(o == null){throw new NullPointerException();}
if(!obs.contains(o)){
obs.addElement(o);
}
}
public synchronized void deleteObserver(Observer o){
obs.removeElement(o);
}
public void notifyObservers(){
nitifyObservers(null);//当数据发生改变时通知所有观察者对象进行相应的数据改变
}
具体实现:
Observable是被观察者对象接口,实现该接口就是:目标(被观察者)的具体实现
public class TargetObservable extends Observable
private String msg;
private String getContent(){
return msg;
}
public void setMsg(String msg){
this.msg = msg;
this.setChanged();
this.notifyObservers(msg);
}
public class TargetObserver extends Observer
private String name;
private String getObserverName(){
return name;
}
public void update(Observable arg0,Object arg1){
打印得到的数据内容
}
两种观察者比较
1.为什么不用List? 线程不安全
2.是否有替代品?CopyOnWriteArrayList ,并发库里面的类
5.观察者模式的优点
2.观察者模式在android中的实际运用
回调、ListView的观察者使用、Rxjava观察者模式的使用情况
1.回调模式
实现了抽象类/接口的实例,实现了父类的提供的抽象方法后,将该方法交还给父类处理
onClickListener
2.listView中notifyDataChanged方法
图:
AdapterView中的
void rememberSyncState(){方法
if(mSelectedPosition >= 0){重新绘制}, 这就是为什么滚到顶部 的原因
3.Rxjava中观察模式的运用

11-8_11章结束[00_57_56][20180806-202807-1].jpg

11-8_11章结束[01_01_30][20180806-203455-2].jpg

11-8_11章结束[01_05_08][20180806-203724-3].jpg

11-8_11章结束[01_13_31][20180806-205347-4].jpg

11-8_11章结束[01_16_32][20180806-205515-5].jpg

11-8_11章结束[01_17_48][20180806-205608-6].jpg

11-8_11章结束[01_17_55][20180806-205612-7].jpg

11-8_11章结束[01_19_35][20180806-205721-8].jpg

11-8_11章结束[01_20_28][20180806-205757-9].jpg

11-8_11章结束[01_21_07][20180806-205825-0].jpg

11-8_11章结束[01_21_16][20180806-205831-1].jpg

11-8_11章结束[01_22_04][20180806-205904-2].jpg

11-8_11章结束[01_22_49][20180806-205935-3].jpg

11-8_11章结束[01_23_14][20180806-205952-4].jpg

11-8_11章结束[01_23_35][20180806-210014-5].jpg

11-8_11章结束[01_23_49][20180806-210023-6].jpg

11-8_11章结束[01_25_01][20180806-210113-7].jpg

11-8_11章结束[01_25_51][20180806-210304-8].jpg
网友评论