Transfer of control in Observer pattern
I am trying to implement observer pattern for my project. The LeaveFields
class extends Observable
and LeaveGenerator
implements Observer
.
private class LeaveFields extends Observable {
private User user;
private Date date;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
setChanged();
notifyObservers(user);
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
setChanged();
notifyObservers(date);
}
}
private class LeaveGenerator implements Observer {
@Override
public void update(Observable observable, Object object) {
开发者_运维问答 if (object instanceof User) {
System.out.println("==============User============");
} else if (object instanceof Date) {
System.out.println("==============Date============");
}
}
}
What I am doing is that, during the execution, any changes to the user or date will force LeaveGenerator
to do some work. The changes to date is made by some code snippet like: leaveFields.setDate(date);
. I am trying to understand the process of transferring control for any changes made. So far I found after executing leaveFields.setDate(date);
that is doing some change, control shifted to the update
method of observer.
//some code
leaveFields.setDate(date);
// code segments following this line wait until the update method of observer returns.
After update
method finish its task the control returns. The current execution pauses temporarily while update
is working.
Am I right and this is my question? At first I thought that the update
is made in different thread.
I presume you're using java.util.Observable
.
Yes the single thread of execution will enter notifyObservers
and callback to each registered Observer
. If you want to asynchronously notify the observers (so the call to notifyObservers()
does not block until each has been called back) you will need to code explicitly for that. As a reference here is the relevant source from java.util.Observable
:
private boolean changed = false;
private Vector obs = new Vector();
public void notifyObservers() {notifyObservers(null);}
public void notifyObservers(Object paramObject){
Object[] arrayOfObject;
synchronized (this){
if (!(this.changed))
return;
arrayOfObject = this.obs.toArray();
clearChanged();
}
for (int i = arrayOfObject.length - 1; i >= 0; --i)
((Observer)arrayOfObject[i]).update(this, paramObject);
}
精彩评论