定义对象间的一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生改变时,会通知所有观察者对象,使它们能够自动更新自己。
例子:
定义观察者与被观察者
public interface Watcher
{
public void update();
}
public class Mother implements Watcher
{
@Override
public void update()
{
System.out.println("妈妈在看着");
}
}
public class Father implements Watcher
{
@Override
public void update()
{
System.out.println("爸爸在看着");
}
}
public interface Watched
{
public void addWatcher(Watcher watcher);
public void removeWatcher(Watcher watcher);
public void notifyWatcher();
}
public class Baby implements Watched
{
List<Watcher> watcherList = new ArrayList<>();
@Override
public void addWatcher(Watcher watcher)
{
watcherList.add(watcher);
}
@Override
public void removeWatcher(Watcher watcher)
{
if (watcherList.contains(watcher))
{
watcherList.remove(watcher);
}
}
@Override
public void notifyWatcher()
{
for (Watcher watcher : watcherList)
{
watcher.update();
}
}
}
测试类
public static void main(String[] args)
{
Father father;
Baby baby = new Baby();
father = new Father();
baby.addWatcher(father);
baby.addWatcher(new Mother());
baby.notifyWatcher();
System.out.println();
baby.removeWatcher(father);
baby.notifyWatcher();
}
结果
爸爸在看着
妈妈在看着
妈妈在看着
我的理解就是,定义观察者,确定在一定情况下,要做什么
然后呢,定义被观察者,它可以增加删除它的观察者,并可通知观察者何时可以行动
使用RxJava实现
下面的demo ,是先生成被观察者,负责通知观察者变化。观察者做一些反馈
public class BabyObservable extends Observable
{
public void cry()
{
System.out.println("宝宝哭了");
setChanged();
notifyObservers();
}
}
public class FatherObserver implements Observer
{
FatherObserver (BabyObservable babyObservable){
babyObservable.addObserver(this);
}
@Override
public void update(Observable observable, Object data)
{
System.out.println("爸爸过了照顾了");
}
}
public class MotherObserver implements Observer
{
MotherObserver (BabyObservable babyObservable)
{
babyObservable.addObserver(this);
}
@Override
public void update(Observable observable, Object data)
{
System.out.println("妈妈过了照顾了");
}
}
public class BabyTest
{
public static void main(String[] args) throws Exception
{
BabyObservable mBabyObservable = new BabyObservable();
FatherObserver fatherObserver = new FatherObserver(mBabyObservable);
MotherObserver motherObservaer = new MotherObserver(mBabyObservable);
mBabyObservable.cry();
}
}
结果:
宝宝哭了
妈妈过了照顾了
爸爸过了照顾了