线程安全的观察者模式
先来说下观察者模式,其实在Android开发中,我们使用观察者模式的时候还是非常多的,无论是广播使用的发布-订阅模式,还是listview的notifyDataSetChanged,或者是RxJava的使用,都是观察者模式的运用。今天就来重新看一下观察者模式。
概念
订阅模式,又称观察者模式。定义对象间一种一对多的依赖关系(注册),使得当一个对象改变状态后,则所有依赖它的对象都会得到通知并被自动更新(通知)。说白了就是个注册,通知的过程。
观察者模式的UML图
- Subject主题,也就是被观察者Observable
简单使用观察者模式
先来定下一种场景,我每个月都会在微信上,收到房东的房租单(跪舔有房的大佬们),假设房东是被观察者,我是观察者,租客我把联系方式留给房东这就是一个注册过程,每个月月初,房东大佬都会通知我们交租(被观察者变化通知观察者)。
JDK为我们提供了Observer与Observable内置接口,我们可以很方便的使用它们。
public class TheOppressed implements Observer {
public String name;
public TheOppressed(String name){
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
System.out.println(name +" 收到要交租信息");
}
}
public class Exploiter extends Observable {
public void postChange(String content){
setChanged();
notifyObservers(content);
}
}
public static void main(String[] args) {
Exploiter exploiter = new Exploiter();
TheOppressed theOppressed1 = new TheOppressed("打工仔1");
TheOppressed theOppressed2 = new TheOppressed("打工仔2");
TheOppressed theOppressed3 = new TheOppressed("打工仔3");
exploiter.addObserver(theOppressed1);
exploiter.addObserver(theOppressed2);
exploiter.addObserver(theOppressed3);
exploiter.postChange("打工仔们快来交房租啦~~");
}
其实往往观察者模式我们自己也可以来写,而不用系统提供的方式
/**
* 观察者
*/
public interface MyObserver {
/**
* 找我
* @param content 找我啥事
*/
void callMe(String content);
}
/**
* 被观察者
*/
public interface MySubject {
/**
* 观察者注册
*/
void registerObserver(MyObserver observer);
/**
* 删除观察者
*/
void removeObserver(MyObserver observer);
/**
* 主题有变化时通知观察者
*/
void notifyObserver();
}
先定义两个接口,实现了观察者模式的基本方法
/**
* 房东
*/
public class Exploiter implements MySubject