概述
Android中的观察者模式是对象间的一种一对多的依赖关系,当一个对象发生改变时,所有依赖于它的对象都会得到通知并且做出相应的更新。
观察者模式的实现比较简单,主要就是定义并维护以下几个角色:
1、观察者接口:这个接口中一般会定义一个接收通知的方法。
2、具体的观察者:观察者接口的具体实现类,在收到通知时做具体的响应操作。
3、被观察者接口:这个接口中定义了被观察者需要做的事情,通常这些事情包括:注册观察者、解注册观察者、消息通知。
4、具体的被观察者:被观察者接口的具体实现类,这个实现类中一般会有一个观察者对象的集合,用于注册时添加观察者对象、解注册时删除观察者对象、消息更新时遍历集合通知所有的观察者。
公交车可以看做是一个被观察者,乘客是观察者,当公交车到站时就通知乘客可以上车了。
定义观察者接口:
public interface IPassenger {
void onBusArrived(int busID);
}
定义具体的观察者:
public class Passenger implements IPassenger {
private String busID;
private String passengerName;
//用于标记是否上车
private boolean isOnTheBus;
public Passenger(String name, String busID) {
passengerName = name;
this.busID = busID;
}
@Override
public void onBusArrived(String busID) {
if (this.busID.equalsIgnoreCase(busID)) {
Log.i("TAG", passengerName + ":是我那一班公交,我要上车。");
isOnTheBus = true;
} else {
Log.i("TAG", passengerName + ":不是我那一班公交,不上车。");
isOnTheBus = false;
}
}
public boolean isOnTheBus() {
return isOnTheBus;
}
}
定义被观察者接口:
public interface IBus {
//注册观察者
void registerPassenger(IPassenger passenger);
//解注册观察者
void unRegisterPassenger(IPassenger passenger);
//消息通知
void notifyBusArrived();
}
定义具体被观察者接口:
public class Bus implements IBus {
//保存观察者对象的集合
private List<IPassenger> passengers = new ArrayList<>();
private String busID;
public Bus(String busID) {
this.busID = busID;
}
@Override
public void registerPassenger(IPassenger passenger) {
//添加观察者
if (!passengers.contains(passenger)) {
passengers.add(passenger);
}
}
@Override
public void unRegisterPassenger(IPassenger passenger) {
//删除观察者
int index = passengers.indexOf(passenger);
if (index != -1) {
passengers.remove(index);
}
}
@Override
public void notifyBusArrived() {
//通知所有注册的观察者
for (IPassenger passenger : passengers) {
passenger.onBusArrived(busID);
}
}
}
public class DemoActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
//观察者对象
Bus bus = new Bus();
//被观察者对象
Passenger passenger01 = new Passenger("passenger01", "G001");
Passenger passenger02 = new Passenger("passenger02", "G84");
Passenger passenger03 = new Passenger("passenger03", "G001");
//注册观察者
bus.registerPassenger(passenger01);
bus.registerPassenger(passenger02);
bus.registerPassenger(passenger03);
//通知
bus.notifyBusArrived();
//如果上车了就解注册
if (passenger01.isOnTheBus()) {
bus.unRegisterPassenger(passenger01);
}
if (passenger02.isOnTheBus()) {
bus.unRegisterPassenger(passenger02);
}
if (passenger03.isOnTheBus()) {
bus.unRegisterPassenger(passenger03);
}
}
}
在Android JDK中自带有Observer接口和Observable类。Observer中定义有update方法,我们可以定义一个观察者类实现这个Observer接口。Observable类中主要定义有以下几个方法:
1、addObserver:添加观察者对象。
2、deleteObserver:删除观察者对象。
3、notifyObservers:通知观察者,这个方法有两个重载,一个带参数,一个不带参数。
4、deleteObservers:删除所有的观察者
5、setChanged:用来标记内容状态发生了改变,我们在调用notifyObservers之前需要先调用这个方法。
Observer接口:
public interface Observer {
/**
* This method is called whenever the observed object is changed. An
* application calls an <tt>Observable</tt> object's
* <code>notifyObservers</code> method to have all the object's
* observers notified of the change.
*
* @param o the observable object.
* @param arg an argument passed to the <code>notifyObservers</code>
* method.
*/
void update(Observable o, Object arg);
}
Observable类:
public class Observable {
private boolean changed = false;
private Vector<Observer> obs;
/** Construct an Observable with zero Observers. */
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() {
notifyObservers(null);
}
public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal;
synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
* needs synchronization, but notifying observers
* does not (should not). The worst result of any
* potential race-condition here is that:
* 1) a newly-added Observer will miss a
* notification in progress
* 2) a recently unregistered Observer will be
* wrongly notified when it doesn't care
*/
// Android-changed: Call out to hasChanged() to figure out if something changes.
// Upstream code avoids calling the nonfinal hasChanged() from the synchronized block,
// but that would break compatibility for apps that override that method.
// if (!changed)
if (!hasChanged())
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
public synchronized void deleteObservers() {
obs.removeAllElements();
}
protected synchronized void setChanged() {
changed = true;
}
protected synchronized void clearChanged() {
changed = false;
}
public synchronized boolean hasChanged() {
return changed;
}
public synchronized int countObservers() {
return obs.size();
}
}
以下是基于JDK中的Observer接口和Observable类实现的Bus和Passenger之间的观察者模式:
定义观察者实现类:
public class Passenger implements Observer {
private String busID;
private String passengerName;
//用于标记是否上车
private boolean isOnTheBus;
public Passenger(String name, String busID) {
passengerName = name;
this.busID = busID;
}
@Override
public void update(Observable o, Object arg) {
if (arg.toString().equalsIgnoreCase(busID)) {
Log.i("TAG", passengerName + ":是我那一班公交,我要上车。");
isOnTheBus = true;
} else {
Log.i("TAG", passengerName + ":不是我那一班公交,不上车。");
isOnTheBus = false;
}
}
public boolean isOnTheBus() {
return isOnTheBus;
}
}
定义具体的被观察者:
public class Bus extends Observable {
public void notifyBusArrived(String busID) {
//标记数据改变
setChanged();
//通知观察者
notifyObservers(busID);
}
}
public class DemoActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
//观察者对象
Bus bus = new Bus();
//被观察者对象
Passenger passenger01 = new Passenger("passenger01", "G001");
Passenger passenger02 = new Passenger("passenger02", "G84");
Passenger passenger03 = new Passenger("passenger03", "G001");
//注册观察者
bus.addObserver(passenger01);
bus.addObserver(passenger02);
bus.addObserver(passenger03);
//消息通知
bus.notifyBusArrived("G001");
//解注册
if (passenger01.isOnTheBus()){
bus.deleteObserver(passenger01);
}
if (passenger02.isOnTheBus()){
bus.deleteObserver(passenger02);
}
if (passenger03.isOnTheBus()){
bus.deleteObserver(passenger03);
}
}
}
从上面可以看出使用JDK中自带的Observer和Observable实现观察者模式会少写许多代码,但是其内部实现原理和我们自定义观察者接口和被观察者接口是一样的。
最后
以上就是平淡小蚂蚁为你收集整理的Android中的观察者模式的全部内容,希望文章能够帮你解决Android中的观察者模式所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复