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
notifyObserversand callback to each registeredObserver. If you want to asynchronously notify the observers (so the call tonotifyObservers()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 fromjava.util.Observable: